python - 不知道如何将其合并到我的代码中
问题描述
我的代码应该输出这种格式:'姓氏,名字 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]
解决方案
您的代码会使此任务复杂化。您可以简单地遍历 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()
根据环境使用。
推荐阅读
- javascript - 如何使用 jQuery 将一个字段的内容复制到另一个字段
- php - 函数作为数组值一个元素
- javascript - 如何解决 React 中获取响应的编码问题?
- azure - 将数据写入 Azure EventHub 连接超时问题
- java - 如何在使用 Spring 创建期间配置 kafka 主题保留策略?
- excel - Excel VBA 自动筛选字段作为变量
- r - 将 .txt 作为一个单元格上传以进行进一步编辑
- regex - Intellij:正则表达式匹配失败 - 匹配文件内容时产生堆栈溢出
- objective-c - 为什么这个条件会导致错误?
- node.js - mongodb 聚合 $lookup 与查找和填充