wkwkwk
wkwkwk

Reputation: 163

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

Upvotes: 5

Views: 3480

Answers (6)

ahmed
ahmed

Reputation: 1

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

Upvotes: 0

yatu
yatu

Reputation: 88236

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

Upvotes: 6

lmiguelvargasf
lmiguelvargasf

Reputation: 69755

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'

Upvotes: 0

kederrac
kederrac

Reputation: 17322

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

Upvotes: 0

The Niv
The Niv

Reputation: 135

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

Upvotes: 0

xnx
xnx

Reputation: 25518

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)

Upvotes: 1

Related Questions