【问题标题】:Validating user input strings in Python在 Python 中验证用户输入字符串
【发布时间】:2013-05-14 03:48:00
【问题描述】:

所以我搜索了“字符串”、“python”、“验证”、“用户输入”等单词的几乎所有排列,但我还没有找到适合我的解决方案.

我的目标是提示用户是否要使用字符串“yes”和“no”开始另一个事务,我认为字符串比较在 Python 中将是一个相当简单的过程,但有些东西只是工作不正常。我使用的是 Python 3.X,所以据我所知,输入应该是一个字符串而不使用原始输入。

即使输入'yes'或'no',程序总是会回退无效输入,但真正奇怪的是,每次我输入一个长度> 4个字符或一个int值的字符串时,它都会检查它作为有效的正输入并重新启动程序。我还没有找到获得有效否定输入的方法。

endProgram = 0;
while endProgram != 1:

    #Prompt for a new transaction
    userInput = input("Would you like to start a new transaction?: ");
    userInput = userInput.lower();

    #Validate input
    while userInput in ['yes', 'no']:
        print ("Invalid input. Please try again.")
        userInput = input("Would you like to start a new transaction?: ")
        userInput = userInput.lower()

    if userInput == 'yes':
        endProgram = 0
    if userInput == 'no':
        endProgram = 1

我也试过

while userInput != 'yes' or userInput != 'no':

我将不胜感激,不仅可以帮助我解决我的问题,而且如果有人有任何关于 Python 如何处理字符串的额外信息,那将是非常棒的。

如果其他人已经问过这样的问题,请提前抱歉,但我已尽力搜索。

谢谢大家!

~戴夫

【问题讨论】:

    标签: python string validation input


    【解决方案1】:

    您正在测试用户输入 yes 还是 no。添加not

    while userInput not in ['yes', 'no']:
    

    稍微快一点,更接近你的意图,使用一组:

    while userInput not in {'yes', 'no'}:
    

    您使用的是userInput in ['yes', 'no'],如果userInput 等于'yes''no',则为True

    接下来,使用布尔值设置endProgram

    endProgram = userInput == 'no'
    

    因为您已经验证了userInputyesno,所以无需再次测试yesno 来设置您的标志变量。

    【讨论】:

    • 哇。这么简单的错误。感谢您的及时回复。我想有时你只需要第二双眼睛就能发现事物。
    • 附带说明一下,您能否帮我了解一下为什么我原来的 while userInput != 'yes' 或 userInput != 'no': 方法不起作用?
    • @user2398870:如果userInput 设置为'yes',则!= 'no' 为True。那不是你想要测试的。 :-) 将 or 更改为 and 将使该版本正常工作。
    【解决方案2】:
    def transaction():
    
        print("Do the transaction here")
    
    
    
    def getuserinput():
    
        userInput = "";
        print("Start")
        while "no" not in userInput:
            #Prompt for a new transaction
            userInput = input("Would you like to start a new transaction?")
            userInput = userInput.lower()
            if "no" not in userInput and "yes" not in userInput:
                print("yes or no please")
            if "yes" in userInput:
                transaction()
        print("Good bye")
    
    #Main program
    getuserinput()
    

    【讨论】:

      猜你喜欢
      • 2016-06-12
      • 1970-01-01
      • 2015-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多