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

标签 python string validation input

所以我几乎搜索了“字符串”、“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 如何处理字符串的任何其他信息,那将是非常好的。

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

谢谢大家!

~戴夫

最佳答案

您正在测试用户输入是否 yesno .添加 not :

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

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

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

你用的是userInput in ['yes', 'no'] ,即 True如果userInput等于'yes''no' .

接下来,使用 bool 值设置endProgram :

endProgram = userInput == 'no'

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

关于python - 在 Python 中验证用户输入的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16635073/

相关文章:

python - Pandas 更改所有列上的列数据类型

python - 如何使用 Flask 和 flask_jwt_extended 进行自定义 JWT 验证?

python - pip 目标并在 setup.py 中安装后

xml - 我在我的 XSD 中指定什么来跳过 xml 标记的属性验证

python - Flask 永久 session : where to define them?

ruby - 字符串中的十六进制字符

string - 如何在C#中逐个字符分隔字符串并在后面添加符号

java - 解析 XML 并将结果存储在字符串中

Jquery Validate - 使用远程查看 MySQL 数据库中是否存在某个实例

php - 验证更新表格