J.C
J.C

Reputation: 105

Python: Reverse Order Of Words

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!

Upvotes: 3

Views: 1523

Answers (7)

s_baldur
s_baldur

Reputation: 33498

Using regex:

import re
ex2 = re.sub('(\w+)\s(\w+)', r'\2, \1', ex1)

>>> ex2
'Doe, John'

Upvotes: 0

Ma0
Ma0

Reputation: 15204

In addition to the many answers posted, I would like to highlight Python multiple assignment schema and the newly-introduced f-strings (3.6+) which in your case could be used as:

name, surname = ex1.split(' ')
ex2 = f"{surname}, {name}"

Upvotes: 2

AKX
AKX

Reputation: 168834

Something like

ex1 = 'John Doe Smith Brown'
print(', '.join(ex1.split(None, 1)[::-1]))

should do the trick.

The output is "Doe Smith Brown, John". If you actually wanted "Brown, Smith, Doe, John", remove that , 1 parameter (which tells .split() to only allow one split).

Upvotes: 3

Madhan Varadhodiyil
Madhan Varadhodiyil

Reputation: 2116

This should work

 ext = ", ".join( reversed(ex1.split(" ")))

Upvotes: 1

rahlf23
rahlf23

Reputation: 9019

This should work for your example:

', '.join(ex1.split()[::-1])

Upvotes: 2

jpp
jpp

Reputation: 164613

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.

Upvotes: 5

R Balasubramanian
R Balasubramanian

Reputation: 809

Given that you will always have names in "First Last" format, here's a really simple solution:

name = ex1.split(' ')
ex2 = name[1] + ', ' + name[0]

>>> ex2
'Doe, John'

Upvotes: 3

Related Questions