在 Python 中,如何检查用户是否输入了名称而不是数字? [英] In Python, how do I check that the user has entered a name instead of a number?

查看:79
本文介绍了在 Python 中,如何检查用户是否输入了名称而不是数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,当要求用户输入字符串时,如何检查用户是否输入了名称而不是数字?我想要以他们的名字形式输入的字符串,但我想使用错误检查来确保用户没有输入数字.

解决方案

您可以定义一个函数来确定输入字符串中是否有任何非字母字符:

def is_valid_name(s):return all(char.isalpha() for char in s)

如果字符串中存在个字母字符,则返回True,否则返回False.

<预><代码>>>>打印(is_valid_name(Hello123"))错误的>>>打印(is_valid_name(你好"))真的

请注意,这不适用于空格:

<预><代码>>>>打印(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 中,如何检查用户是否输入了名称而不是数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆