Python Forum
Can 'len(s)' be used to just count letters?
Thread Rating:
  • 2 Vote(s) - 2.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Can 'len(s)' be used to just count letters?
#1
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.
Reply
#2
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_'))
Unless noted otherwise, code in my posts should be understood as "coding suggestions", and its use may require more neurones than the two necessary for Ctrl-C/Ctrl-V.
Your one-stop place for all your GIMP needs: gimp-forum.net
Reply
#3
Thanks for the fast reply.

Python is pretty amazing I'm clearly a beginner Big Grin .
Reply
#4
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.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Row Count and coloumn count Yegor123 4 1,321 Oct-18-2022, 03:52 AM
Last Post: Yegor123

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020