O.rka
O.rka

Reputation: 30687

How can I check if character in a string is a letter? (Python)

I know about islower and isupper, but can you check whether or not that character is a letter? For Example:

>>> s = 'abcdefg'
>>> s2 = '123abcd'
>>> s3 = 'abcDEFG'
>>> s[0].islower()
True

>>> s2[0].islower()
False

>>> s3[0].islower()
True

Is there any way to just ask if it is a character besides doing .islower() or .isupper()?

Upvotes: 227

Views: 730705

Answers (9)

Guillaume F.
Guillaume F.

Reputation: 1130

Easier way that considers only letters a-z and A-Z:

myString = "Hi!"

for char in myString:
    if "a" <= char <= "z" or "A" <= char <= "Z":
        print(f"{char}: letter")
    else:
        print(f"{char}: not letter")

Which gives output:

H: letter
i: letter
!: not letter

Note that if "char" has multiple characters, this will only consider the first character.

Upvotes: 1

NeuroMorphing
NeuroMorphing

Reputation: 149

I have developed a Python package called Alphabetic which can be used to check whether a string contains only letters or not. One special feature of Alphabetic is that it can check whether a character or a whole string consists of valid letters on the basis of a language, so it is not limited to the English alphabet.

First, install the package via: pip install alphabetic

Next, import it and create a WritingSystem instance that allows you to access Alphabetic's core functions:

from alphabetic import WritingSystem

ws = WritingSystem()    

Now, let us check if the strings you have given belong to the script type category alphabet:

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

print(ws.is_alphabet(s1)) # True
print(ws.is_alphabet(s2)) # False
print(ws.is_alphabet(s3)) # True

Now let's look at non-English strings (here: Hebrew):

s4 = 'אבגדה1978'
s5 = 'רשת'
s6 = '!+םנןסעפףצץ&?'

print(ws.is_abjad(s4)) # False
print(ws.is_abjad(s5)) # True
print(ws.is_abjad(s6)) # False

Please note that the is_alphabet function is not selected here, as the Hebrew letters do not belong to the alphabet script type, but to abjad.

Here you can see which languages are supported.

Upvotes: 0

ron_g
ron_g

Reputation: 1663

If you want to test only a-z and A-Z (i.e. exclude 中 as valid), you can do:

def validate_word(word):
    """ Only allow a-z and A-Z only """
    valid_chars = {'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','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'}
    if set(word).difference(valid_chars):
        print('there\'s at least 1 char that\'s not allowed')

Haven't timed it but pretty using a set would be faster than iterating chars

Upvotes: 0

amalik2205
amalik2205

Reputation: 4162

This works:

any(c.isalpha() for c in 'string')

Upvotes: 4

omry
omry

Reputation: 11

This works:

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.")

Upvotes: -1

Chandan Sharma
Chandan Sharma

Reputation: 2519

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)

Output:

Please Enter Letters with Numbers:
abcdefg hi j 12345
Result:
Letters = 10
Digits = 5

By using str.isalpha() you can check if it is a letter.

Upvotes: 3

rainer
rainer

Reputation: 7099

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

Upvotes: 341

MII
MII

Reputation: 57

I found a good way to do this with using a function and basic code. This is a code that accepts a string and counts the number of capital letters, lowercase letters and also 'other'. Other is classed as a space, punctuation mark or even Japanese and Chinese characters.

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.")

Upvotes: 4

Legolas Bloom
Legolas Bloom

Reputation: 1805

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)
>>>

Upvotes: 45

Related Questions