在Python中输入或raw_input之后的字符串验证

时间:2016-04-04 03:03:22

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

我想针对某些条件测试输入的字符串。在这个例子中,我希望变量中的字符串至少包含一个数字字符...

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”这样的字符串

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:4)

您必须遍历输入字符串:

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

答案 1 :(得分:1)

肯定有比这更好的方法:

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