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.

ex.
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:

1 Like

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!

3 Likes

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
3 Likes

Sorry to revive an old topic, but looking at old conversations I felt to post in the spirit of remembering a retired mentor. I’ve done my best to provide a Python version of a JS snippet @mtf gave me once, used to count letters in a string.

import re

s = "This sentence has %x letters!"
t = len(''.join(list(filter(lambda x: x != '', re.split('[^\w]', s))))) - 1
u = str(t).join(s.split('%x'))

print(u)

Certainly a bit of an advanced method for a small program but it illustrates the possibilities available within a language, and with it you can compact 4 lines of code into a single one.
A bit further thought is to consider a slightly different method using Python’s list comprehension, since list comprehension is said to be faster than using a lambda:

s = "This sentence has %x letters!"
t = len(''.join([x for x in re.split('[^\w]', s) if x != ''])) - 1
u = str(t).join(s.split('%x'))

print(u)

Certainly not saying you should use either of these methods, and can’t say they would pass in a lesson, but it is an example of what can be done in a language.

3 Likes