![](/img/trans.png)
[英]How do I replace a certain amount of zeros in a string with an amount that the user is asked to input, starting from the end of the string?
[英]How do I replace a certain string in a list from user input?
我制作了一個列表,其中包含許多名稱和一個菜單,其中包含用戶可以用來更改列表的選項。 選項之一是將列表中的名稱之一替換為用戶輸入的任何內容。 如何才能做到這一點? 我更喜歡不使用索引
到目前為止我的代碼:
print("==================")
names = ["Chris", "Dave", "Joseph", "Harvey", "Levi"]
print(names)
print("==================")
print("(A) Add a name \n(B) Change a name \n(C) Delete a name \n(D) View all names \n(Q) Quit ")
print("==================")
while True:
choice = input("Select an option: ").lower()
if choice == "a":
newName = input("Enter a new name: ")
names.append(newName)
elif choice == "b":
oldName = input("What name would you like to replace?: ")
newName = input("Enter a new name: ")
# I don't know what to put here
elif choice == "c":
delete = input("Which name do you want to remove?: ")
names.remove(delete)
elif choice == "d":
print(names)
elif choice == "q":
print("Goodbye")
break
在這里使用索引確實是一個好主意,您可以在用戶查找時查找特定索引。
elif choice == "b":
oldName = input("What name would you like to replace?: ")
newName = input("Enter a new name: ")
i = names.index(oldName)
names[i] = newName
添加驗證以確保在輸入不在列表中的名稱時應用程序不會崩潰也很有用。 就像是:
if oldName in names:
i = names.index(oldName)
names[i] = newName
else:
print("That name is not in the list")
可以將相同的驗證添加到刪除選項中。
elif choice == "b":
oldName = input("What name would you like to replace?: ")
newName = input("Enter a new name: ")
names = [x if x != oldName else newName for x in names ]
print(names)
如果名稱不等於oldName
,您可以使用列表推導添加名稱,如果名稱不等於oldName
則添加newName
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.