简体   繁体   中英

Count number of letters in string (not characters, only letters)

I've tried looking for an answer but I'm only finding how to count the number of characters. I need to know how to count the number of letters within a string. Also need to know how to count the number of numbers in a string.

For example:

"abc 12"

the output would be

letters: 3 numbers: 2

You have string methods for both cases. You can find out more on string — Common string operations

s = "abc 12"

sum(map(str.isalpha, s))
# 3
sum(map(str.isnumeric, s))
# 2

Or using a generator comprehension with sum :

sum(i.isalpha() for i in s)
# 3
sum(i.isnumeric() for i in s)
# 2

Something like:

s = 'abc 123'
len([c for c in s if c.isalpha()])
3

would work.

Also, since you True evaluates as 1 and False as 0, you can do:

sum(c.isalpha() for c in s)

You can use string.isdigit() which checks if a string(or character) contains only digits and string.isalpha() which checks if a string(or character) contains only characters and do this

str='abc 123'
nums=len([char for char in str if char.isdigit()])
chars=len([char for char in str if char.isalpha()])

you can try:

s = 'abc 12'

p = [0 if c.isalpha() else 1 if c.isnumeric() else -1 for c in s]

letters, numeric = p.count(0), p.count(1)

print(letters, numeric)

output:

3 2

Asumming you are using Python 3.6+, I think using generator expressions , the sum function and a f-strings could solve your problem:

>>> s = 'abc 12'
>>> numbers = sum(i.isnumeric() for i in s)
>>> letters = sum(i.isalpha() for i in s)
>>> f'letters: {letters} numbers: {numbers}'
'letters: 3 numbers: 2'

You can do that using lambda function with one line of code :)

counter = lambda word,TYPE: len([l for l in word if l.isalpha()]) if TYPE == str else len([n for n in word if n.isdigit()]) if TYPE == int else len([c for c in word if c.strip()]) if TYPE == all else TypeError("expected 'str' or 'int' or 'all' of 'TYPE' argument")

word = "abcd 123"

lettersCounter = counter(word, str) # >= 4
numbersCounter = counter(word, int) # >= 3
allCounter = counter(word, all) # >= 7

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM