在 Python 中验证用户输入字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16635073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:13:34  来源:igfitidea点击:

Validating user input strings in Python

pythonstringvalidationinput

提问by user2398870

So I've searched just about every permutation of the words "string", "python", "validate", "user input", and so on, but I've yet to come across a solution that's working for me.

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

My goal is to prompt the user on whether or not they want to start another transaction using the strings "yes" and "no", and I figured that string comparison would be a fairly easy process in Python, but something just isn't working right. I am using Python 3.X, so input should be taking in a string without using raw input, as far as I understand.

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

The program will always kick back invalid input, even when entering 'yes' or 'no', but the really weird thing is that every time I enter a a string > 4 characters in length or an int value, it will check it as valid positive input and restart the program. I have not found a way to get valid negative input.

该程序将始终回退无效输入,即使输入“是”或“否”,但真正奇怪的是,每次我输入长度超过 4 个字符的字符串或整数值时,它都会将其检查为有效正数输入并重新启动程序。我还没有找到获得有效负输入的方法。

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

I have also tried

我也试过

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

I would greatly appreciate not only help with my problem, but if anyone has any additional information on how Python handles strings that would be great.

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

Sorry in advance if someone else has already asked a question like this, but I did my best to search.

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

Thanks all!

谢谢大家!

~Dave

~戴夫

采纳答案by Martijn Pieters

You are testing if the user input isyesor no. Add a not:

您正在测试用户输入是否为yesno。添加一个not

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

Ever so slightly faster and closer to your intent, use a set:

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

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

What you used is userInput in ['yes', 'no'], which is Trueif userInputis either equal to 'yes'or 'no'.

您使用的是userInput in ['yes', 'no'],即TrueifuserInput要么等于'yes'要么'no'

Next, use a boolean to set endProgram:

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

endProgram = userInput == 'no'

Because you already verified that userInputis either yesor no, there is no need to test for yesor noagain to set your flag variable.

因为你已经验证了userInput或者是yesno,没有必要测试yesno重新设置你的标志变量。

回答by MrTg

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()