1

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?

3
  • 1
    The "issue" is it isn't valid syntax. Commented Aug 14, 2014 at 7:59
  • What you have is a list, not a tuple. Commented Aug 14, 2014 at 8:14
  • i meant to say a list of tuples but I thought it was wrong Commented Aug 14, 2014 at 8:19

4 Answers 4

5
>>> '\n'.join(' '.join(str(y) for y in x) for x in locations)
'John 32 21\nMichael 23 12'
Sign up to request clarification or add additional context in comments.

Comments

2

[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

1 Comment

The lambda isn't necessary in this case (map(str, elem)). Without it, this would be the shortest answer.
1

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)

Comments

1

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 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.