重写名称(重新排列和修改字符串)

时间:2017-01-28 02:32:10

标签: python string list

我正在尝试编写一个给出名称的代码,首先返回姓氏,后跟逗号,后跟第一个名称(如果有),后跟每个剩余/中间名的第一个字母每封信后都有一段时间。如果中间名是单个字母,请不要将其缩写/按句点跟随。

我已经把它用于基础工作(即Karen Anne Carpenter - > Carpenter,Karen A.(未显示的代码)但是如何让它适用于Bryan J Phil K Smith - &gt ;史密斯,布莱恩J P. K?(没有一个字母的中间名称)。

def rewrite(name):
    space = " "
    l = [i for i in range(len(name)) if name.startswith(" ", i, i+1)] #i gives index of every space, l[i] gives list of these indexes
    for i in range(len(l)-1): 
        if name[l[i]+2] == " ": #middle name is only one letter, print name[l[i]+1] as is
            shortMiddleInitial = name[l[i] + 1]
    #missing return?
        if name[l[i]+2] != " ": #middle name is more than one letter, take initial and period
            middleInitial = name[l[i] + 1] + "."
    #missing return?

1 个答案:

答案 0 :(得分:0)

快速而肮脏的解决方案:

def rewrite(name):
    parts = name.split()
    lastname = parts[-1]
    if len(parts) > 1:
        firstname = parts[0]
    else:
        return lastname  # if no firstname there are no middles, just return
    if len(parts) > 2:
        # If you don't want 1-letter middle names to be followed by a "." change it to "len > 1".
        middles = [c[0] + '.' if len(c) >= 1 else c for c in parts[1:-1]]
    else:
        middles = []
    return '{}, {} {}'.format(lastname, firstname, ' '.join(middles)).strip()

这适用于多个输入:

>>> rewrite('Bryan J Phil K Smith')
'Smith, Bryan J. P. K.'

>>> rewrite('Karen Anne Carpenter')
'Carpenter, Karen A.'

>>> rewrite('Funny')
'Funny'

>>> rewrite('Pete Funny')
'Funny, Pete'