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

查看:438
本文介绍了如何检查字符串在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:

str.isalpha() is only true if all characters in the string are letters:


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

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

Demo:

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

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

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