嗨,我今天刚刚开始学习python并开始应用我在flash卡程序上学到的东西,我想问用户他们的名字,并且只接受没有数字或符号的字母,我尝试了几种方法但是那里是我在尝试中遗漏的东西。这是我到目前为止所做的。
yname = raw_input('Your Name ?: ')
if yname.isdigit():
print ('{0}, can\'t be your name!'.format(yname))
print "Please use alphbetic characters only!."
yname = raw_input("Enter your name:?")
print "Welcome %s !" %yname
但我认为,如果用户输入任何一个角色不止一次,它最终会继续......所以我这样做了。
yname = raw_input("EnterName").isalpha()
while yname == True:
if yname == yname.isalpha():
print "Welcome %s " %(yname)
else:
if yname == yname.isdigit():
print ("Name must be alphabetical only!")
yname = raw_input('Enter Name:').isalpha()
这个while循环一直在继续,我尝试了( - )和(+)原始输入变量,正如我在一些教程中看到的那样。所以我想到了使用while循环。
name = raw_input("your name"):
while True:
if name > 0 and name.isalpha():
print "Hi %s " %name
elif name < 0 and name.isdigit():
print "Name must be Alphabet characters only!"
try:
name != name.isalpha():
except (ValueError):
print "Something went wrong"
答案 0 :(得分:1)
您可以稍微重新安排上次尝试以获得所需内容:
while True:
name = raw_input("your name") # ask inside the loop
if name and name.isalpha():
print "Hi %s " %name
break # leave the loop if done
elif name and name.isdigit():
print "Name must be Alphabet characters only!"
else:
print "Please enter something"
请注意,如果if name
,True
将为name != ""
。
答案 1 :(得分:1)
使用regexes:
import re
regex = re.compile("^[a-zA-Z]+$")
valid_name = False
while not valid_name:
user_name = raw_input("EnterName")
if not regex.search(user_name):
print "this can't be your name"
else:
print "Hi there, {0}".format(user_name)
valid_name = True
另外,请注意programmers often make false assumptions about human names
编辑:作为替代方案,您可以跳过编译正则表达式并只使用该模式:
if not re.search("^[a-zA-Z]+$", user_name):
...
但是,由于你在循环编译版本中执行它会有稍微好一点的性能,因为re.search
实际上每次调用后都在后台编译正则表达式。
此外,请注意我已将match
更改为search
,并稍微修改了正则表达式,因为some differences因此search
符合您的情况更多。
答案 2 :(得分:1)
name = raw_input('Enter your name: ')
while not name.isalpha():
print 'Invaid characters in name'
name = raw_input('Enter your name: ')
答案 3 :(得分:1)
这将检查raw_input中的两个字母,并检查我在上次尝试时尝试做的名称长度。
import string
import re
name = re.compile(r'[a-zA-Z]+') #This will check for alphabet.
yname = raw_input("Your Name:") #ask the user for input.
while not name.match(yname):
print "invalid characters"
yname = raw_input("Your Name:")
if 5<=len(yname)<=10:
print "Hi,", yname, "!"
elif len(yname)>10:
print "too long!"
elif len(yname)<5:
print "too short!"