如何检查字符串是否仅包含 Python 中的字母? [英] How can I check if a string only contains letters in Python?

查看:18
本文介绍了如何检查字符串是否仅包含 Python 中的字母?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查一个字符串是否只包含字母,而不是数字或符号.

I'm trying to check if a string only contains letters, not digits or symbols.

例如:

>>> only_letters("hello")
True
>>> only_letters("he7lo")
False

推荐答案

简单:

if string.isalpha():
    print("It's all letters")

str.isalpha() 只为真如果字符串中的所有个字符都是字母:

如果字符串中的所有字符都是字母并且至少有一个字符,则返回 true,否则返回 false.

Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.

演示:

>>> 'hello'.isalpha()
True
>>> '42hello'.isalpha()
False
>>> 'hel lo'.isalpha()
False

这篇关于如何检查字符串是否仅包含 Python 中的字母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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