我可以让我的用户输入接受 int 或 string 值吗? (Python)

Can I make my user input accept either int or string values? (Python)

我目前正在做一个项目,想知道是否可以让我的输入接受 int 或 str 值。这是到目前为止的代码:

`NumOfKeys = int(input("你想添加多少个键:"))

    for i in range(NumOfKeys):
        TypeInput = input("Is your key:value a string or int value? (str/int/both)")
        if TypeInput.lower() == "str":
            KeyInput = input("Please input your key")
            ValueInput = input("Please input your value")
        elif TypeInput.lower() == "int":
            KeyInput = int(input("Please input your key"))
            ValueInput = int(input("Please input your value"))
        elif TypeInput.lower() == "both":
            # I want the key to be either str or int
            # I want the value to be either str or int`

python 中的输入将 return 一个字符串。 将输入存储在变量中后,如果需要,您可以尝试使用 int() 函数将其解析为 int,但它将首先存储为字符串。

试试这个:

NumOfKeys = int(input("How many keys would you like to add:"))
for i in range(NumOfKeys):
    KeyInput = input("Please insert your key")
    if KeyInput.isdigit():
        TypeInput = int(KeyInput)
    ValueInput =input("Please input your value")
    if ValueInput.isdigit():
        ValueInput = int(ValueInput)

希望就是你想要的。让我知道是否可以。 如果键同时包含数字和字符,则必须是字符串。