我是python编码的新手,需要知道如何只允许用户在输入名称时输入字母.因此,如果他们输入一个数字或根本不输入任何数字,我希望代码说"请仅使用字母,再试一次".
干杯克里斯
你要求的是一个str.isalpha()功能:
isalpha(...)
S.isalpha() -> bool
Return True if all characters in S are alphabetic
and there is at least one character in S, False otherwise.
Run Code Online (Sandbox Code Playgroud)
例如,您可以像这样使用它:
def ask_name():
while True:
name = raw_input("What is your name?")
if name.isalpha():
return name
else:
print("Please use only letters, try again")
Run Code Online (Sandbox Code Playgroud)