How to count number of letters in a string? (beginner)

I would like to count the number of letters in a string but I do not know how to. I used len() first but that method included both the letters and spaces in the string.

my_string = “this sentence has xx letters”
print len(my_string)
it would say 28 instead of 24

Is there a way to only count the letters within a string?

thanks in advance :herb:

You could remove the spaces using .replace(' ', ''), then use len() on that string:

var_a = "hello world!"
var_b = var_a.replace(" ", '')
print(len(var_b))#would give 11

This removes the spaces (by way of replacing them with '', or nothing). It then counts the remaining characters.
I hope this helps!

1 Like

In the event that you need to only count letters, you can also use .isalpha() to check if each character is a letter.

When used on a string it returns True if the string is a letter in the alphabet:

print('s'.isalpha()) #prints True
print('1'.isalpha()) #prints False

If you have learned about for loops than you could use one to go through each character in the string, and add one to a variable for each letter.

I would suggest trying on your own, though if you need it here is an example
sentence = "Hello World!"
num_letters = 0

for character in sentence:
  if character.isalpha():
    num_letters += 1

print(num_letters) #prints 10
1 Like