如何检查字符串中的字符是否为字母?Python

2024-04-19 19:11:18 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我知道islower和isupper,但我好像不知道你能不能检查那个字符是否是字母?

Example:

s = 'abcdefg'
s2 = '123abcd'
s3 = 'abcDEFG'

s[0].islower() = True
s2[0].islower()= False
s3[0].islower()=True

除了执行.islower()或.isupper()之外,还有什么方法可以直接询问它是字符吗?


Tags: 方法falsetrues3example字母字符s2
3条回答
str.isalpha()

如果字符串中的所有字符都是字母,并且至少有一个字符,则返回true,否则返回false。字母字符是Unicode字符数据库中定义为“字母”的字符,即具有“Lm”、“Lt”、“Lu”、“Ll”或“Lo”中的“general category”属性的字符。请注意,这与Unicode标准中定义的“字母”属性不同。

在python2.x中:

>>> s = u'a1中文'
>>> for char in s: print char, char.isalpha()
...
a True
1 False
中 True
文 True
>>> s = 'a1中文'
>>> for char in s: print char, char.isalpha()
...
a True
1 False
� False
� False
� False
� False
� False
� False
>>>

在python3.x中:

>>> s = 'a1中文'
>>> for char in s: print(char, char.isalpha())
...
a True
1 False
中 True
文 True
>>>

此代码有效:

>>> def is_alpha(word):
...     try:
...         return word.encode('ascii').isalpha()
...     except:
...         return False
...
>>> is_alpha('中国')
False
>>> is_alpha(u'中国')
False
>>>

>>> a = 'a'
>>> b = 'a'
>>> ord(a), ord(b)
(65345, 97)
>>> a.isalpha(), b.isalpha()
(True, True)
>>> is_alpha(a), is_alpha(b)
(False, True)
>>>

您可以使用^{}

例如:

s = 'a123b'

for char in s:
    print(char, char.isalpha())

输出:

a True
1 False
2 False
3 False
b True

我找到了一个使用函数和基本代码的好方法。 这是一个代码,它接受一个字符串,并计算大写字母、小写字母和“其他”的数量。另一种被归类为空格、标点符号,甚至是日文和中文。

def check(count):

    lowercase = 0
    uppercase = 0
    other = 0

    low = 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'
    upper = 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'



    for n in count:
        if n in low:
            lowercase += 1
        elif n in upper:
            uppercase += 1
        else:
            other += 1

    print("There are " + str(lowercase) + " lowercase letters.")
    print("There are " + str(uppercase) + " uppercase letters.")
    print("There are " + str(other) + " other elements to this sentence.")

相关问题 更多 >