How can I check if character in a string is a letter? (Python)
You can use str.isalpha()
.
For example:
s = 'a123b'
for char in s:
print(char, char.isalpha())
Output:
a True
1 False
2 False
3 False
b True
str.isalpha()
Return true if all characters in the string are alphabetic and there is at least one character, false otherwise. Alphabetic characters are those characters defined in the Unicode character database as “Letter”, i.e., those with general category property being one of “Lm”, “Lt”, “Lu”, “Ll”, or “Lo”. Note that this is different from the “Alphabetic” property defined in the Unicode Standard.
In 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
>>>
In python3.x:
>>> s = 'a1中文'
>>> for char in s: print(char, char.isalpha())
...
a True
1 False
中 True
文 True
>>>
This code work:
>>> 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)
>>>