3

I have a list of tuples, where all emlements in the tuples are strings. It could look like this:

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

I want to convert this to a string so it would look like 'a b c d e'. I can use ' '.join( ... ) but I'm unsure of what argument I should use.

user3599828
  • 331
  • 8
  • 14

6 Answers6

5

You can flatten the list, then use join:

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

or with list comprehension:

>>> ' '.join([i for sub in my_list for i in sub])
'a b c d e'
fredtantini
  • 15,966
  • 8
  • 49
  • 55
2
>>> my_list = [('a', 'b', 'c'), ('d', 'e')]
>>> ' '.join(' '.join(i) for i in my_list)
'a b c d e'
Irshad Bhat
  • 8,479
  • 1
  • 26
  • 36
  • When using `str.join` you should use a list comprehension, not a generator expression. See [this answer](http://stackoverflow.com/a/9061024/3005188). – Ffisegydd Dec 31 '14 at 17:49
1

You can use a list comprehension which will iterate over the tuples and then iterate over each tuple, returning the item for joining.

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

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

The list comprehension is equivalent to:

a = []
for tup in my_list:
    for item in tup:
        a.append(item)
Ffisegydd
  • 51,807
  • 15
  • 147
  • 125
1
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'
Shahriar
  • 13,460
  • 8
  • 78
  • 95
0
my_list = [('a', 'b', 'c'), ('d', 'e')]
print "".join(["".join(list(x)) for x in my_list])

Try this.

vks
  • 67,027
  • 10
  • 91
  • 124
0

List comprehension is the best one liner solution to your question :-

my_list = [('a', 'b', 'c'), ('d', 'e')]
s = ' '.join([elem for item in my_list for elem in item])
Pabitra Pati
  • 457
  • 4
  • 12