How to convert a list of tuples to one string

I have a list of tuples where all characters in the tuples are strings. It might look like this:

my_list = [('a', 'b', 'c'), ('d', 'e')]

      

I want to convert this to a string so that it looks like "abcd e". I can use '.join (...), but I'm not sure which argument I should be using.

+3


source to share


6 answers


You can flatten the list and then use join:

>>> import itertools
>>> ' '.join(itertools.chain(*my_list))
'a b c d e'

      



or with a list:

>>> ' '.join([i for sub in my_list for i in sub])
'a b c d e'

      

+5


source


>>> my_list = [('a', 'b', 'c'), ('d', 'e')]
>>> ' '.join(' '.join(i) for i in my_list)
'a b c d e'

      



+2


source


You can use a list comprehension, which will iterate over the tuples and then iterate over each tuple, returning the element to join.

my_list = [('a', 'b', 'c'), ('d', 'e')]

s = ' '.join([item for tup in my_list for item in tup])

      

Understanding a list is equivalent to:

a = []
for tup in my_list:
    for item in tup:
        a.append(item)

      

+1


source


my_list = [('a', 'b', 'c'), ('d', 'e')]

L = []

for x in my_list:
    L.extend(x) 

print ' '.join(L)


output:
'a b c d e'

      

+1


source


my_list = [('a', 'b', 'c'), ('d', 'e')]
print "".join(["".join(list(x)) for x in my_list])

      

Try it.

0


source


List comprehension is the best liner solution to your question:

my_list = [('a', 'b', 'c'), ('d', 'e')]
s = ' '.join([elem for item in my_list for elem in item])

      

0


source







All Articles