首页 > 解决方案 > 不知道如何将其合并到我的代码中

问题描述

我的代码应该输出这种格式:'姓氏,名字 MI' 但是......如果中间的首字母只是一个字母(例如 name = "Bala X Krish"),它不应该在后面加上句号MI(应该返回“Krish,Bala X”)。

现在,我的代码正在返回“Krish,Bala X”。

我该如何解决它,以便仅在单字母 MI 的这个特定实例中,不添加结束时间?

def modify(name):
    """
    name is a string with zero or more spaces
    with one space between each "word"
    return string "last, first MI. MI. MI. ..."
    where MI is middle initial
    """
    NameLst = name.split() 

    MiddleNames = NameLst[1:-1]

    initial = ""

    if " " not in name:
        return name
    elif name.count(" ") == 1:
        return NameLst[-1] + ", " + NameLst[0]
    else:
        MiddleNameCount = len(MiddleNames)
        for MiddleName in MiddleNames:
            Keep = MiddleName[0] + "."
            if MiddleNameCount == 1: 
                    initial = initial + Keep + " "
            elif MiddleNameCount > 1:
                    if MiddleName[0:-2]:
                        initial = initial + Keep + " "
                    elif MiddleName[-1]:
                        initial = initial + Keep
        x = NameLst[-1] + ", " + NameLst[0] + " " + initial 
        return x[0:-1]

标签: pythonpython-3.x

解决方案


您的代码会使此任务复杂化。您可以简单地遍历 middleNames 并检查它们的长度:

def modify(name):
    """
    name is a string with zero or more spaces
    with one space between each "word"
    return string "last, first MI. MI. MI. ..."
    where MI is middle initial
    """
    nameLst = name.split()
    if len(nameLst) < 2:
        return name

    middleNames = nameLst[1:-1]

    initial = f"{nameLst[-1]}, {nameLst[0]}"

    for i in middleNames:
        initial += f" {i[0]}"
        if len(i) != 1: initial += '.'

    return initial

请记住,使用 f-Strings ( f"") 进行格式化仅在 python 3.6+ 中可用,因此您可能需要.format()根据环境使用。


推荐阅读