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!
.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.
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.
a = [('A', 'B', 'C'), ('B', 'C', 'A'), ('C', 'B', 'B')]
print ["".join(line) for line in a]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With