我的导师责成我制作一台ID打印机'我想让程序在输入你的名字时不接受整数但是通过这样做它不会接受整体字符串。我的代码如下。
User_Name = ""
def namechecker():
print("Please Input Your name")
User_Name = str(input(":"))
while User_Name == "":
print("Please input your name")
User_Name = str(input(":"))
while User_Name != str():
print("Please use characters only")
print("Please input your name")
User_Name = input (":")
print("Thankyou, ", User_Name)
namechecker()
答案 0 :(得分:1)
你的问题很不清楚。阅读完之后,我认为你想获得一个只有字母字符的用户名。您可以使用str.isalpha
:
def getUserName():
userName = ''
while userName == '' or not userName.isalpha():
userName = input('Please input your name: ')
if not userName.isalpha():
print('Please use alphabet characters only')
return userName
userName = getUserName()
print('Thank you, {}'.format(userName))
答案 1 :(得分:0)
如果您想了解检查数字的想法,还可以检查字符串是否只包含带有str.isdigit()的数字
像这样:
def namechecker():
User_Name = ""
while True:
User_Name = input("Please input your name: ") # input will always be a string
if User_Name.isdigit(): # check if the string contains only digits // returns True or False
print("Please use chracters only")
continue # stay inside the loop if the string contains only digits
else: break # leave the loop if there are other characters than digits
print("Thankyou, ", User_Name)
namechecker()
请注意,如果给定字符串包含仅数字,此代码将仅询问另一个输入。如果你想确保一个字符串只包含字母字符,你可以使用string.isalpha()
def namechecker():
User_Name = ""
while True:
User_Name = input("Please input your name: ")
if not User_Name.isalpha():
print("Please use chracters only")
continue
else: break
print("Thankyou, ", User_Name)
namechecker()
这样可以解决问题,输入中不允许使用任何数字。但是,您应该阅读Built-in Types上的文档。