user3132888
user3132888

Reputation: 23

Python and flipping the order of lastname, firstname

I have a string such as smith, bob;jones, bill;doe, john that is coming from a CSV file. I would like to extract the names and flip the order of the last name and first name to be first name then last name.

I tried the example shown in switch-lastname-firstname but that example does not work for me.

I also tried:

namelist = ['smith, bob;jones, bill;doe, john']
n2=''
for n in namelist:
    name = n.partition(',')
    fn = name[2]
    ln = name[0]
    n2 += fn + ' ' + ln + ';'

However - it doesn't separate out the names but Works fine if there is only one name instead of a list of names... What can I do to correct this?

Upvotes: 2

Views: 5847

Answers (3)

Buddhima Gamlath
Buddhima Gamlath

Reputation: 2328

Here is a so-called python one liner...

s = 'smith, bob;jones, bill;doe, john'

result = ';'.join([("%s, %s" % (fn, ln)) for ln, fn in [tuple(k.split(",")) for k in s.split(";")]]).strip() 

But, as it seems like you are new to python, here is and step by step explanation...

#First, you need to separate the names and create a list of names. This is done by,
listOfNames = s.split(";")

#Then, each item in the name is split into first and last names and a list of tuples is created.
listOfNameTuples = [tuple(name.split(",")) for name in listOfNames]

#Then, the reversed name tuples can be created with this.
listOfNameTuples2 = [(fn, ln) for (ln, fn) in listOfNameTuples]

#Then tuple items are merged to reversed name strings.
listOfNames2 = ["%s, %s" % (fn, ln) for (fn, ln) in listOfNameTuples2]

#Finally, they are joined together, seperated with a ";" and leading and trailing spaces are removed with `.Strip()`
result = ";".join(listOfNames2).strip() 

Upvotes: 0

Enrico Morelli
Enrico Morelli

Reputation: 173

s = 'smith, bob;jones, bill;doe, john'
f = s.split(';')
for ll in f:
   lname, fname = ll.split(',')
   print fname, lname

Upvotes: 1

Hannes Ovrén
Hannes Ovrén

Reputation: 21831

Quite simple using the split function.

s = 'smith, bob;jones, bill;doe, john'
for lname, fname in [q.split(",") for q in s.split(";")]:
    print fname, lname

This will output

bob smith
bill jones
john doe

Upvotes: 6

Related Questions