-4

I retrieved data from a sql query and

I have a list of 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?

Notice the ',' at the end of each tuple... I have difficulty to get rid of it

Below the Radar
  • 7,321
  • 11
  • 63
  • 142

5 Answers5

2

If you're using Python 2.x, then you can use:

>>> a = [(34.2424, -64.2344, 76.3534, 45.2344)]
>>> print ' '.join(map(str, a[0]))
'34.2424 -64.2344 76.3534 45.2344'

In Python 3.x, or Python 2.x with a from __future__ import print_function, you can use:

>>> print(*a[0])
34.2424 -64.2344 76.3534 45.2344

You seem to have updated the format of the input data, so:

First element from each tuple...

>>> a = [(34.2424,), (-64.2344,), (76.3534,), (45.2344,)]
>>> print ' '.join(str(el[0]) for el in a)
34.2424 -64.2344 76.3534 45.2344

More than one element in each tuple...

>>> from itertools import chain
>>> print(*chain.from_iterable(a))
34.2424 -64.2344 76.3534 45.2344

However, it does seem you just want a tuple...

>>> tuple(chain.from_iterable(a))
(34.2424, -64.2344, 76.3534, 45.2344)

Which you can then just use str on to make it a str if you so wanted...

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
1

str.join() only works on strings, so you have to cast them to strings first. I could write that out, but I just read something in the Python Cookbook (my new favorite book) about this, so I'll link to that instead. Beazley and Jones write that for printing a tuple like this, instead of turning each one into a string, you can simply do:

tup = (34.2424, -64.2344, 76.3534, 45.2344)
print(*tup)

As your tuple is nested inside a list, you can either iterate through the list and print thusly, or you can flatten the list before working with it (and there are a lots of answers on SO, and a nice one in the Python Cookbook, on flattening nested sequences).

Edit: I noticed the title changed to a request to flatten the list of tuples to a tuple, which is a flattening nested sequences request.

I'll link to the Python Cookbook recipe I noted above called "flattening a nested sequence" and also state again that there are lots of answers on this here at SO: "Flattening a Nested Sequence"

erewok
  • 7,555
  • 3
  • 33
  • 45
1

Sorry I misread your question, but didn't vote down.

>>> data = [(34.2424,), (-64.2344,), (76.3534,), (45.2344,)]
>>> data_str = '(' + ', '.join(map(lambda x: str(x[0]), a)) + ')'
>>> print data_str
(34.2424, -64.2344, 76.3534, 45.2344)
>>> 

or just flatten the list and use str to get the resulting tuple as a string.

>>> data_str = str(sum(data, ()))
RussW
  • 427
  • 4
  • 11
0
" ".join(tuple)

Will do the job, assuming you would like space separators.

Steve Barnes
  • 27,618
  • 6
  • 63
  • 73
-2

The join function of strings will do it.

print " ".join(arrayOfValuesYouWantToJoinTogether)
will
  • 10,260
  • 6
  • 46
  • 69