如何检查字符串中是否只包含Python中的字母?

时间:2013-09-06 22:17:48

标签: python string conditional-statements

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

例如:

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

9 个答案:

答案 0 :(得分:75)

简单:

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

str.isalpha()仅在字符串中所有字符为字母时才为真:

  

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

演示:

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

答案 1 :(得分:15)

str.isalpha()功能有效。即

if my_string.isalpha():
    print('it is letters')

答案 2 :(得分:9)

对于通过Google发现此问题的人可能想知道字符串是否只包含所有字母的子集,我建议使用正则表达式:

import re

def only_letters(tested_string):
    match = re.match("^[ABCDEFGHJKLM]*$", tested_string)
    return match is not None

答案 3 :(得分:6)

string.isalpha()功能对您有用。

请参阅http://www.tutorialspoint.com/python/string_isalpha.htm

答案 4 :(得分:5)

看起来有人说要使用str.isalpha

这是检查所有字符是否都是字母的单行函数。

def only_letters(string):
    return all(letter.isalpha() for letter in string)

all接受一个可迭代的布尔值,如果所有布尔值均为True,则返回True

更一般地说,如果您的iterable中的对象被视为all,则True会返回True。这些将被视为False

  • 0
  • None
  • 空数据结构(即:len(list) == 0
  • False。 (杜)

答案 5 :(得分:5)

实际上,我们现在处于21世纪的全球化世界中,人们不再仅仅使用ASCII进行通信,因此当关于"的问题仅仅是字母和#34;你还需要考虑非ASCII字母表中的字母。 Python有一个非常酷的unicodedata库,其中包括Unicode字符的分类:

unicodedata.category('陳')
'Lo'

unicodedata.category('A')
'Lu'

unicodedata.category('1')
'Nd'

unicodedata.category('a')
'Ll'

categories and their abbreviations在Unicode标准中定义。从这里你很容易就可以得到这样的函数:

def only_letters(s):
    for c in s:
        cat = unicodedata.category(c)
        if cat not in ('Ll','Lu','Lo'):
            return False
    return True

然后:

only_letters('Bzdrężyło')
True

only_letters('He7lo')
False

正如您所看到的,白名单类别可以通过函数内部的元组轻松控制。有关更详细的讨论,请参阅this article

答案 6 :(得分:2)

(1)打印字符串时使用 str.isalpha()

(2)请查看以下程序供您参考: -

 str = "this";  # No space & digit in this string
 print str.isalpha() # it gives return True

 str = "this is 2";
 print str.isalpha() # it gives return False

注意: - 我在Ubuntu中查看了上面的示例。

答案 7 :(得分:1)

您可以利用正则表达式。

>>> import re
>>> pattern = re.compile("^[a-zA-Z]+$")
>>> pattern.match("hello")
<_sre.SRE_Match object; span=(0, 5), match='hello'>
>>> pattern.match("hel7lo")
>>>

如果找到匹配项,则match()方法将返回一个Match对象。否则,它将返回None


一种更简单的方法是使用.isalpha()方法

>>> "Hello".isalpha()
True
>>> "Hel7lo".isalpha()
False

isalpha()如果字符串中至少有1个字符并且字符串中的所有字符均为字母,则返回true。

答案 8 :(得分:-2)

我提出的一个非常简单的解决方案:(Python 3)

    def only_letters(tested_string):
        for letter in tested_string:
            if not letter in "abcdefghjklmnopqrstuvwxyz":
                return False
        return True

如果要允许空格,可以在要检查的字符串中添加空格。

相关问题