Python: Reverse Order Of Words

  • A+
Category:Languages

In my program I pull a string from another file and assign it to a variable (see below)

ex1 = 'John Doe' 

How would I convert the above string to a different format as seen below? (Note the space after the comma)

ex2 = 'Doe, John' 

Sorry if this question seems trivial but I haven't had much experience with lists and most solutions incorporate lists (so I don't fully understand them).

Any help would be greatly appreciated!

 


For the case of 2 names, you can use str.join with reversed and str.split:

ex1 = 'John Doe' ex2 = ', '.join(reversed(ex1.split()))  # 'Doe, John' 

You can also use f-strings (Python 3.6+) via an anonymous function:

ex2 = (lambda x: f'{x[1]}, {x[0]}')(ex1.split())  # 'Doe, John' 

It's not clear what you'd like to see for multiple names, e.g. if middle names are provided.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: