我知道islower
and isupper
,但你能检查那个字符是否是一个字母吗?例如:
>>> s = 'abcdefg'
>>> s2 = '123abcd'
>>> s3 = 'abcDEFG'
>>> s[0].islower()
True
>>> s2[0].islower()
False
>>> s3[0].islower()
True
.islower()
除了 do or之外,还有什么方法可以问它是否是一个角色.isupper()
?
您可以使用str.isalpha()
.
例如:
s = 'a123b'
for char in s:
print(char, char.isalpha())
输出:
a True
1 False
2 False
3 False
b True
str.isalpha()
如果字符串中的所有字符都是字母并且至少有一个字符,则返回 true,否则返回 false。字母字符是在Unicode 字符数据库中定义为“字母”的字符,即一般类别属性为“Lm”、“Lt”、“Lu”、“Ll”或“Lo”之一的字符。请注意,这与 Unicode 标准中定义的“Alphabetic”属性不同。
在 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)
>>>
我找到了一个使用函数和基本代码的好方法。这是一个接受字符串并计算大写字母、小写字母以及“其他”的数量的代码。其他被归类为空格、标点符号甚至日文和中文字符。
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.")
data = "abcdefg hi j 12345"
digits_count = 0
letters_count = 0
others_count = 0
for i in userinput:
if i.isdigit():
digits_count += 1
elif i.isalpha():
letters_count += 1
else:
others_count += 1
print("Result:")
print("Letters=", letters_count)
print("Digits=", digits_count)
输出:
Please Enter Letters with Numbers:
abcdefg hi j 12345
Result:
Letters = 10
Digits = 5
通过使用str.isalpha()
,您可以检查它是否是一个字母。
这有效:
any(c.isalpha() for c in 'string')
这有效:
word = str(input("Enter string:"))
notChar = 0
isChar = 0
for char in word:
if not char.isalpha():
notChar += 1
else:
isChar += 1
print(isChar, " were letters; ", notChar, " were not letters.")