Python实现逗号分隔人名的拆分与标准化格式转换
人名格式转换的Pythonic实现方法
需求说明
我有以下两种字符串格式的人名:
"DOE D, John"
以及:
"DOE, Jane"
需要将它们分别转换为:
"John D Doe"
和:
"Jane Doe"
我的尝试与问题
我自己编写了一段Python代码:
name = "DOE, John" name_list = [] comma = "," for letter in name: name_list.append(letter) index_comma = name_list.index(",") last_name = name_list[:index_comma] first_name = name_list[index_comma:] print('The primary list is: ',name_list) print("First half of list is ",first_name) print("Second half of list is ",last_name) new_name_list = first_name + last_name for letter in new_name_list: if letter == comma: new_name_list.pop() print(''.join(new_name_list))
但运行后得到的错误结果是:
, JohnDO
请问如何用简洁、符合Python风格的方式实现该需求?
解决方案
通用实现函数
直接利用字符串的分割与拼接特性,写一个通用函数就能处理两种格式:
def format_name(name_str): # 按逗号分割字符串,同时去除各部分的多余空格 last_part, first_part = name_str.split(',') return f"{first_part.strip()} {last_part.strip()}" # 测试示例 print(format_name("DOE D, John")) # 输出: John D Doe print(format_name("DOE, Jane")) # 输出: Jane Doe
代码逻辑说明
- 分割字符串:
split(',')会把输入字符串按逗号拆成两部分,比如"DOE D, John"会被拆成["DOE D", " John"]; - 清理空格:
strip()方法去除字符串前后的空白字符,把" John"变成"John",保证拼接后格式整洁; - 拼接结果:用f-string直接按「名字部分 + 姓氏部分」的顺序拼接,自动生成目标格式。
原代码出错原因
你手动将字符串转为列表操作的逻辑绕了弯路:
- 分割后拼接的列表包含逗号,遍历删除逗号时,
pop()默认删除列表最后一个元素,而非逗号本身,导致姓氏被截断,逗号却留在开头,最终得到错误结果。用字符串原生的分割、拼接方法可以完全避免这种复杂且易出错的操作。
内容的提问来源于stack exchange,提问作者Programmer0403
相关产品推荐
相关产品推荐

