20

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?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Below the Radar
  • 7,321
  • 11
  • 63
  • 142

6 Answers6

41

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 :).

Community
  • 1
  • 1
TerryA
  • 58,805
  • 11
  • 114
  • 143
  • In Python 3, your answer is good because ``map()`` is a generator in Python 3. But in Python2, it would be better to use ``imap()`` – eyquem Aug 26 '13 at 06:43
  • 2
    @eyquem actually it's faster and more efficient to use a list comp rather than a generator for a join: http://stackoverflow.com/a/9061024/1240268 – Andy Hayden Sep 19 '13 at 03:00
  • @AndyHayden Wow, that's very interesting. Thanks for the link! – TerryA Sep 19 '13 at 03:02
  • @AndyHayden Thank you very very much for your link. The information given by the Raymond Hettinger's answer and the discussion between Raymond and ovgolovin is very interesting. - I upvote two of your best answers seen in your user's page – eyquem Sep 19 '13 at 10:44
  • I have the exact same speed using map or list comprehension, ie: 1.87 usec per loop – Below the Radar Oct 06 '16 at 18:25
  • @BelowtheRadar Perhaps for such a small tuple, yes, but for much bigger tuples there will be bigger differences – TerryA Oct 06 '16 at 20:36
6

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.

mattsilver
  • 4,386
  • 5
  • 23
  • 37
5

If I've got your message, you are getting tuple of floats, am I right?

If so, the following code should work:

In [1]: t = (34.2424 , -64.2344 , 76.3534 , 45.2344)

In [2]: ' '.join([str(x) for x in t])
Out[2]: '34.2424 -64.2344 76.3534 45.2344'

We're converting every value in tuple to string here, because str.join method can work only with lists of string. If t is a tuple of strings the code will be just ' '.join(t).

In case you're getting string in format "(34.2424 , -64.2344 , 76.3534 , 45.2344)", you should firstly get rid of unnescessary parthensis and commas:

In [3]: t = "(34.2424 , -64.2344 , 76.3534 , 45.2344)"

In [4]: t.strip('()')
Out[4]: '34.2424 , -64.2344 , 76.3534 , 45.2344'

In [5]: numbers = t.strip('()')

In [6]: numbers.split(' , ')
Out[6]: ['34.2424', '-64.2344', '76.3534', '45.2344']

In [7]: ' '.join(numbers.split(' , '))
Out[7]: '34.2424 -64.2344 76.3534 45.2344'
utter_step
  • 633
  • 7
  • 14
4

Try this

>>> a = (34.2424, -64.2344, 76.3534, 45.2344)
>>> ' '.join(str(i) for i in a)
'34.2424 -64.2344 76.3534 45.2344
Roman Pekar
  • 107,110
  • 28
  • 195
  • 197
  • 1
    Writing ``[str(i) for i in a]``, it means that a list object is first created before ``' '.join()`` has to work. But it's possible to write ``' '.join(str(i) for i in a)`` : in this case, ``join()`` gets every ``str(i)`` as they are furnished one after the other by the generator ``str(i) for i in a)``. See also my comment to Haidro's answer. – eyquem Aug 26 '13 at 06:49
  • Actually list comprehension is better with join: http://stackoverflow.com/a/9061024/1240268 – Andy Hayden Sep 19 '13 at 03:01
  • Thanks Andy, thanks for noting that, I've read this question about 2 days ago, but I've already fotgot that I have some answers on this topic. i'm learning python with SO :) – Roman Pekar Sep 19 '13 at 03:53
1
rows = cursor.fetchall()

for row in rows:#iterate over entire rows
    print('row : 'row)#prints the entire row
    for d in row:#prints each item of the row
        print(d)

Output:

row :  (34.2424, -64.2344, 76.3534, 45.2344)
34.2424
-64.2344
76.3534
45.2344
Udesh
  • 2,415
  • 2
  • 22
  • 32
-1

You could simply use the following code:

i = 0
for row in data:
       print(row[i])
       i++
peacetype
  • 1,928
  • 3
  • 29
  • 49
Ethan Brimhall
  • 357
  • 3
  • 10