为什么使用.isalnum的代码不起作用?

时间:2016-05-11 18:59:36

标签: python

name = ""
name = input("Hi there, what is your name? ")
while name.isalnum():
   name = input("Hi there, what is your name? ")
while name.isdigit():
   name = input("Hi there, what is your name? ")

这是代码的样子,但我只希望它只接受字母。然而,当我运行此代码时,出现问题并且程序一直询问所提供的任何输入的用户名称,程序继续的唯一方法是按下“空格(条形)”。这有什么问题?

2 个答案:

答案 0 :(得分:3)

while name.isalnum():

表示只要name是字母数字,循环将继续运行。你想要:

while not name.isalnum():

答案 1 :(得分:0)

通过regex

可以更好地实现目标
import re
p=re.compile(r'[a-zA-Z\s]+$')
name="user0000"
while not p.match(name):
    name = input("Hi there, what is your name? ")

这将接受像“乔治史密斯”这样的名字而不是“史密斯1980”