Python Forum

Full Version: Can 'len(s)' be used to just count letters?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Good day people.
I recently decided to try out Python and I was wondering if you can use 'len(s)' to only count letters.
For example when you type this

>>>s=mother_of_god
>>>len(s)
you get
13

I was wondering if you could change it to just count the letters (without manual adjustments).
An alternative that I haven't found yet would also suffice.
len() gives the number of elements in a sequence. If yiou want to count the "letters" you have to create a sequence with just the letters. One way to do it it with a  "comprehension:"
len([x for x in 'abcdfeg123_' if x in 'abcdefghijklmnopqrstuvwxyz'])
but on string this can be very inefficient, its is better to remove all the characters you don't want and count the rest:
import re
len(re.sub(^[a-z]','','abcdfeg123_'))
Thanks for the fast reply.

Python is pretty amazing I'm clearly a beginner Big Grin .
When you have a newline character in your string, it's also counted.
You can strip whitespace very easy:

text = 'Hello World\r\n\t'
len(text.strip()) # The method strip creates a new string and removes all whitespace characters
The method strip accepts a string. It cuts the chars in the order from the left and right side.
To get a list of whitespaces, you can import the module string and look into string.whitespace.

  1. type-str
  2. string


If you take the example from Ofnuts, you can use string.ascii_lowercase. It's easier as of typing the letters a-z manual.