如何用逗号分割一串某人的名字,然后将名字、中间名和姓氏大写

问题描述 投票:0回答:1

我有一个这样的名字:

"DOE D, John"

还有这样的名字:

"DOE, Jane"

以字符串的形式

我需要将其转换为这样:

"John D Doe

"Jane Doe"

到目前为止我有这个:

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

我该如何以干净且Pythonic的方式做到这一点?

python string list split capitalize
1个回答
0
投票

您可以使用以下方法:

>>> " ".join(reversed(" ".join("DOE D, John".split(",")).split())).title()
'John D Doe'
>>> " ".join(reversed(" ".join("DOE, Jane".split(",")).split())).title()
'Jane Doe'
  • .split(",")
    分割逗号的左右两侧
  • 内部
    " ".join
    用空格重新组合组件
  • .split()
    拆分所有单词
  • reversed
    颠倒顺序
  • 外层
    " ".join
    重新组合颠倒的词表
  • .title()
    每个单词的第一个字母大写
© www.soinside.com 2019 - 2024. All rights reserved.