Reputation: 729
I don't know a lot about python so please be patient with me:
Let's say we have a tuple that has this form:
locations = [('John' , 32 , 21) , ('Michael' , 23 , 12)]
How can I concatenate them to a string that looks like
"John 32 21
Michael 23 12"
I tried doing this:
str1 = '\n'.join( ' '.join(elem[0] elem [1] elem[2]) for elem in locations)
But I get an error at the elem[0],[1],[2] saying Invalid Syntax
Any ideas on how I can fix this?
Upvotes: 1
Views: 78
Reputation: 51
You can do this:
>>>['%s %s %s' %i for i in locations]
['John 32 21', 'Michael 23 12']
with line feed:
>>>print '\n'.join(['%s %s %s' %i for i in locations])
John 32 21
Michael 23 12
Upvotes: 1
Reputation: 416
[edit] Or try this
>>> '\n'.join([' '.join(map(lambda c: str(c), elem)) for elem in locations])
>>> 'John 32 21\nMichael 23 12'
map(lambda c: str(c), elem) takes every element from locations ie from ('John' , 32 , 21) 'John', 32 and 21 and converts into string and returns ['John', '32', '21'] which is then join using ' ' and finally by '\n'
Updated:
>>> '\n'.join([' '.join(map(str, elem)) for elem in locations])
learned, thanks
Upvotes: 2
Reputation: 180401
Your own code need to have each elem separated by a comma and the three elements wrapped inside a container:
' '.join(elem[0] elem [1] elem[2]) # invalid syntax, join takes a single iterable
'\n'.join( ' '.join((str(elem[0]), str(elem[1]) ,str(elem[2]))) for elem in locations)
You can use unpacking and map to do the same:
'\n'.join( ' '.join(map(str,(a,b,c))) for a,b,c in locations)
Or simply:
'\n'.join( ' '.join(map(str,elem)) for elem in locations)
Upvotes: 1
Reputation: 798606
>>> '\n'.join(' '.join(str(y) for y in x) for x in locations)
'John 32 21\nMichael 23 12'
Upvotes: 5