如何 select 用户字符串输入列表的元素内的元素索引,以逗号分隔?
How to select an index of an element inside an element of a list of a user's string input separated by comma?
用户的输入应该是以逗号分隔的全名列表(与下面的第二个代码相同的输入)。
我想以以下格式在单独的行中打印这些名称:lastname + "," + firstname + middlename
(如果适用)。
我写了两段代码,但我似乎无法将它们组合成我想要的输出:
第一个代码 - 姓名按姓氏 + 逗号 + 名字排序(如果给定则包括中间名):
while True:
name = input("Enter your full name here:").strip().title()
words_in_name = name.split()
surname = words_in_name[-1]
firstname = words_in_name[:-1]
name_sorted = surname, " ".join(firstname)
print(name_sorted)
Enter your full name here: John Doe
('Doe', 'John')
第二个代码 - 全名列表打印在单独的行中,并且在输入中分隔它们的逗号被删除:
while True:
DL_names = input("Enter the list of names you want to add to the DL:").strip().title()
print(*DL_names.split(","), sep='\n')
Enter the list of names you want to add to the DL:John Doe, Jane Doe
John Doe
Jane Doe
您已经拥有让它工作的所有代码片段。您可以通过将 surname
和 firstname
分配给它们各自的拆分字符串索引来使代码更短一些(您也应该首先在 ,
上拆分):
DL_names = input("Enter the list of names you want to add to the DL:").strip().title()
for full_name in DL_names.split(','):
*firstname, surname = full_name.split()
print(f"{surname}, {' '.join(firstname)}")
输出:
Doe, John
Doe, Jane
用户的输入应该是以逗号分隔的全名列表(与下面的第二个代码相同的输入)。
我想以以下格式在单独的行中打印这些名称:lastname + "," + firstname + middlename
(如果适用)。
我写了两段代码,但我似乎无法将它们组合成我想要的输出:
第一个代码 - 姓名按姓氏 + 逗号 + 名字排序(如果给定则包括中间名):
while True:
name = input("Enter your full name here:").strip().title()
words_in_name = name.split()
surname = words_in_name[-1]
firstname = words_in_name[:-1]
name_sorted = surname, " ".join(firstname)
print(name_sorted)
Enter your full name here: John Doe
('Doe', 'John')
第二个代码 - 全名列表打印在单独的行中,并且在输入中分隔它们的逗号被删除:
while True:
DL_names = input("Enter the list of names you want to add to the DL:").strip().title()
print(*DL_names.split(","), sep='\n')
Enter the list of names you want to add to the DL:John Doe, Jane Doe
John Doe
Jane Doe
您已经拥有让它工作的所有代码片段。您可以通过将 surname
和 firstname
分配给它们各自的拆分字符串索引来使代码更短一些(您也应该首先在 ,
上拆分):
DL_names = input("Enter the list of names you want to add to the DL:").strip().title()
for full_name in DL_names.split(','):
*firstname, surname = full_name.split()
print(f"{surname}, {' '.join(firstname)}")
输出:
Doe, John
Doe, Jane