How to transform a tuple to a string of values without comma and parentheses
I retrieved data from a sql query by using
bounds = cursor.fetchone()
And I get a tuple like:
(34.2424, -64.2344, 76.3534, 45.2344)
And I would like to have a string like 34.2424 -64.2344 76.3534 45.2344
Does a function exist that can do that?
Use str.join()
:
>>> mystring = ' '.join(map(str, (34.2424, -64.2344, 76.3534, 45.2344)))
>>> print mystring
34.2424 -64.2344 76.3534 45.2344
You'll have to use map here (which converts all the items in the tuple to strings) because otherwise you will get a TypeError
.
A bit of clarification on the map()
function:
map(str, (34.2424, -64.2344, 76.3534, 45.2344)
is equivalent to [str(i) for i in (34.2424, -64.2344, 76.3534, 45.2344)]
.
It's a tiny bit faster than using a list comprehension:
$ python -m timeit "map(str, (34.2424, -64.2344, 76.3534, 45.2344))"
1000000 loops, best of 3: 1.93 usec per loop
$ python -m timeit "[str(i) for i in (34.2424, -64.2344, 76.3534, 45.2344)]"
100000 loops, best of 3: 2.02 usec per loop
As shown in the comments to this answer, str.join()
can take a generator instead of a list. Normally, this would be faster, but in this case, it is slower.
If I were to do:
' '.join(itertools.imap(str, (34.2424, -64.2344, 76.3534, 45.2344)))
It would be slower than using map()
. The difference is that imap()
returns a generator, while map()
returns a list (in python 3 it returns a generator)
If I were to do:
''.join(str(i) for i in (34.2424, -64.2344, 76.3534, 45.2344))
It would be slower than putting brackets around the list comprehension, because of reasons explained here.
In your (OP's) case, either option does not really matter, as performance doesn't seem like a huge deal here. But if you are ever dealing with large tuples of floats/integers, then now you know what to use for maximum efficiency :).
You can also use str.format()
to produce any arbitrary formatting if you're willing to use *
magic. To handle the specific case of this question, with a single separator, is actually a little cumbersome:
>>> bounds = (34.2424, -64.2344, 76.3534, 45.2344)
>>> "{} {} {} {}".format(*bounds)
34.2424 -64.2344 76.3534 45.2344
A more robust version that handles any length, like join
, is:
>>> len(bounds)*"{} ".format(*bounds)
But the value added is that if you want to extend your formatting to something more involved you've got the option:
>>> "{} --> | {:>10} | {:>10} | {:>10} |".format(*bounds)
34.2424 --> | -64.2344 | 76.3534 | 45.2344 |
From here, your string formatting options are very diverse.