Python并翻转姓氏,名字的顺序

时间:2013-12-24 15:51:38

标签: python string split

我有一个来自CSV文件的smith, bob;jones, bill;doe, john字符串。我想提取名称,并将姓氏和名字的顺序翻转为名字和姓氏。

我尝试了switch-lastname-firstname中显示的示例,但该示例对我不起作用。

我也尝试过:

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

但是 - 如果只有一个名称而不是名单列表,它不会将名称分开但工作正常...我该怎么做才能纠正这个问题?

3 个答案:

答案 0 :(得分:5)

使用split函数非常简单。

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

这将输出

bob smith
bill jones
john doe

答案 1 :(得分:1)

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

答案 2 :(得分:0)

这是一个所谓的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() 

但是,因为你似乎是python的新手,这里是一步一步的解释......

#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()