繁体   English   中英

如何从用户输入替换列表中的某个字符串?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM