用戶的輸入應該是用逗號分隔的全名串列(與下面的第二個代碼相同)。我想以以下格式在單獨的行中列印這些名稱:(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
uj5u.com熱心網友回復:
您已經擁有使其作業的所有代碼。您可以通過將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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/376193.html
下一篇:如何將此矩陣轉換為整數串列?
