[英]How do I replace a certain string in a list from user input?
I made a list which contains a number of names and a menu with options that the user can use to alter the list.我制作了一个列表,其中包含许多名称和一个菜单,其中包含用户可以用来更改列表的选项。 One of the options is to replace one of the names in the list with whatever the user inputs.
选项之一是将列表中的名称之一替换为用户输入的任何内容。 How can this be done?
如何才能做到这一点? I prefer to not use indexes
我更喜欢不使用索引
My code so far:到目前为止我的代码:
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
It really would be a good idea to use index here, and you can look up the specific index at the time the user looks it up.在这里使用索引确实是一个好主意,您可以在用户查找时查找特定索引。
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
It would also be useful to add validation to make sure that the app doesn't crash when a name is entered that isn't in the list.添加验证以确保在输入不在列表中的名称时应用程序不会崩溃也很有用。 Something like:
就像是:
if oldName in names:
i = names.index(oldName)
names[i] = newName
else:
print("That name is not in the list")
The same validation could be added to the delete option.可以将相同的验证添加到删除选项中。
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)
You can use a list comprehension to add the names if the name does not equal oldName
, if the name does equal oldName
then add the newName
instead.如果名称不等于
oldName
,您可以使用列表推导添加名称,如果名称不等于oldName
则添加newName
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.