Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Munging data with '.join' (TypeError: sequence item 0: expected string, tuple found)

I have data in following format:

[('A', 'B', 'C'),
 ('B', 'C', 'A'),
 ('C', 'B', 'B')]

I'm looking to get this:

ABC
BCA
CBB

I'm able to convert one tuple at the time:

>> "".join(data[0])
.. 'ABC'

However when I'm trying to conver the whole list Python gives me an error:

>> "".join(data[:])
.. TypeError: sequence item 0: expected string, tuple found

Any advice how I'll be able to convert the whole list?

Thank you!

like image 338
jjjayn Avatar asked Jan 25 '15 12:01

jjjayn


3 Answers

.join expects a sequence of strings, but you're giving it a sequence of tuples.

To get the result you posted, you'll need to join each element in each tuple, and then join each tuple together:

print('\n'.join(''.join(elems) for elems in data))

This works because .join will accept a generator expression, allowing you to iterate over data (your list of tuples).

We therefore have two joins going on: the inner join builds a string of the three letters (eg, 'ABC'), and the outer join places newline characters ('\n') between them.

like image 78
sapi Avatar answered Oct 20 '22 03:10

sapi


lst=[('A', 'B', 'C'),
 ('B', 'C', 'A'),
 ('C', 'B', 'B')]

for x in lst:
    print ("".join(x))

Output is;

>>> 
ABC
BCA
CBB
>>> 

One-liner;

print ("\n".join(["".join(x) for x in lst]))

You have to reach each element in the list first.

like image 35
GLHF Avatar answered Oct 20 '22 01:10

GLHF


a = [('A', 'B', 'C'),  ('B', 'C', 'A'),  ('C', 'B', 'B')]
print ["".join(line) for line in a]
like image 1
Stavinsky Avatar answered Oct 20 '22 01:10

Stavinsky