Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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

like image 659
wkwkwk Avatar asked Sep 17 '19 19:09

wkwkwk


People also ask

How do you count the number of specific letters in a string?

count(a) is the best solution to count a single character in a string. But if you need to count more characters you would have to read the whole string as many times as characters you want to count.

Can you count with letters?

sort of. We call them Roman numerals. Instead of using numbers like we're familiar with (1, 2, 3, etc.) — which are called Arabic numerals — the ancient Romans developed a numeric system which uses letters of the alphabet.

How do you count only letters in a string Python?

Example: As isalpha() method returns True if the given string contains alphabets. We can count the number of characters of a string by applying this method to every element of this string using a loop. So, we increment a count variable by 1 to count the number of characters in a given string.


1 Answers

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
like image 89
yatu Avatar answered Sep 29 '22 17:09

yatu