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
  • 6
  • 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
  • 14,608
  • 7
  • 46
  • 54
2
>>> my_list = [('a', 'b', 'c'), ('d', 'e')]
>>> ' '.join(' '.join(i) for i in my_list)
'a b c d e'
Irshad Bhat
  • 7,941
  • 1
  • 21
  • 32
  • 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
  • 47,839
  • 14
  • 137
  • 116
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
  • 12,388
  • 6
  • 75
  • 93
0
my_list = [('a', 'b', 'c'), ('d', 'e')]
print "".join(["".join(list(x)) for x in my_list])

Try this.

vks
  • 65,133
  • 10
  • 87
  • 119
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
  • 459
  • 4
  • 12