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
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With