Python - 无法让“string.isalnum():”正常工作

时间:2017-08-01 19:10:30

标签: python

我无法让下面的代码正常工作。如果用户输入名称的数字并且它打印theName.isdigit,则它可以工作。但是,如果用户同时输入数字和字母,则会接受此信息并转到后面的欢迎消息。看看这个,你有没有理由找到为什么theName.isalnum不在这里工作,但上面的那个是?

theName = raw_input ("What is your name?? ")

while theName.isdigit ():
    if theName.isdigit ():
        print "What kind of real name has just numbers in it?? Try again..."
    elif theName.isalnum ():
        print "What kind of name has any numbers in it?? Please try again..."
    elif theName.isalpha ():
        print "Ok, great"
        break
    theName = raw_input ("What is your name?? ")

2 个答案:

答案 0 :(得分:1)

theName = raw_input ("What is your name?? ")

while not theName.isalpha ():
    if theName.isdigit ():
        print "What kind of real name has just numbers in it?? Try again..."
    elif theName.isalnum ():
        print "What kind of name has any numbers in it?? Please try again..."
    theName = raw_input ("What is your name?? ")
print "Ok, great"

while条件应告诉您何时停止循环,即输入isalpha时。然后,因为当输入正确时while循环停止,你可以移动逻辑,以便在循环下面的情况下做什么。

isdigit上循环是有问题的,因为字符串abc123不符合该条件,因此即使名称不符合您的条件,您也会跳出循环。

答案 1 :(得分:0)

正如其他人所说,你的代码存在一些问题。

首先,如果theName包含除数字以外的任何内容,您将永远不会输入while循环,因为isdigit()将返回False

接下来,测试的顺序意味着如果输入的名称包含字母或数字以外的其他内容,则只会进行isalpha()测试。

然而,它也过于复杂。假设您的目标是让用户输入仅由字母组成的名称(即没有空格,数字或特殊字符)

theName = "1" # preseed with invalid value
firstTime = True
while not theName.isalpha():
    if not firstTime:
        print "Your name should not contain anything other than letters"
    theName = raw_input("Please enter your name: ")
    firstTime = False

print "OK, great. Hi " + theName

这将反复提示,直到用户输入有效名称。