问题描述
在 Python 中,当要求用户输入字符串时,如何检查用户是否输入了名称而不是数字?我想要以他们的名字形式输入的字符串,但我想使用错误检查来确保用户没有输入数字.
您可以定义一个函数来确定输入字符串中是否有任何非字母字符:
def is_valid_name(s):return all(char.isalpha() for char in s)
如果字符串中存在仅个字母字符,则返回True
,否则返回False
.
请注意,这不适用于空格:
>>>打印(is_valid_name(你好世界"))错误的因此可以根据需要进行调整:
def is_valid_name(s):返回所有(char.isalpha() 或 char.isspace() for char in s)
看这里:
>>>打印(is_valid_name(你好世界"))真的In Python, how do I check that the user has entered a name instead of a number, when asking for user input as string? I want a string input in the form of their name, but I want to use error checking to make sure the user doesn't enter a number.
You can define a function that determines if there are any non-alphabetic characters in the input string:
def is_valid_name(s):
return all(char.isalpha() for char in s)
This will return True
if only alphabetic characters exist in the string, False
otherwise.
>>> print(is_valid_name("Hello123"))
False
>>> print(is_valid_name("Hello"))
True
Note that this doesn't work with spaces:
>>> print(is_valid_name("Hello World"))
False
So it can be adjusted if necessary:
def is_valid_name(s):
return all(char.isalpha() or char.isspace() for char in s)
See here:
>>> print(is_valid_name("Hello World"))
True
这篇关于在 Python 中,如何检查用户是否输入了名称而不是数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!