【问题标题】:String Validation after input or raw_input in PythonPython中输入或raw_input后的字符串验证
【发布时间】:2016-07-23 11:33:14
【问题描述】:

我想在特定条件下测试输入的字符串。在这种情况下,我希望变量中的字符串至少包含一个数字字符...

while any(inputted.isdigit()) == False:
    print ("Inputted must contain at least one numeric character") # can't figure this one out
    inputted = input("Please enter a combination: ")

理想的输入是像“Boat88Sea”这样的字符串

任何帮助将不胜感激!

【问题讨论】:

  • 您能否举例说明您提供的输入类型? inputted中的典型例子是什么
  • 理想的输入是像“Boat88Sea”这样的字符串

标签: python string python-3.x validation input


【解决方案1】:

您必须遍历输入字符串:

input_string = "" 
while any(c.isdigit() for c in input_string) == False:
    print ("the input string must contain at least one numerical character") 
    input_string = input("Please enter a combination: ")

一旦发现字符串中的任何字符是数字,while循环就会退出。

或者,这可能比您想要的更接近:
只要输入字符串中没有任何字符是数字...

while not any(c.isdigit() for c in inputted):

【讨论】:

  • 你不需要方括号,你可以使用生成器而不是列表。
  • 正确,谢谢;我改变了它 - 但我怀疑它会产生很大的不同,输入不太可能很大。
【解决方案2】:

肯定有比这更好的方法:

cond = True
while cond:
    print ("Inputted must contain at least one numeric character") 
    inputted = input("Please enter a combination: ")
    for x in range(0,9) : 
        if str(x) in inputted : cond = False

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-12
    • 2012-05-10
    • 1970-01-01
    • 2016-04-26
    相关资源
    最近更新 更多