• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

The Programming Expert

Solving All of Your Programming Headaches

  • HTML
  • JavaScript
  • jQuery
  • PHP
  • Python
  • SAS
  • Ruby
  • About
You are here: Home / Python / Count Letters in Word in Python

Count Letters in Word in Python

February 11, 2022 Leave a Comment

In Python, we can easily count the letters in a word using the Python len() function and list comprehension to filter out characters which aren’t letters.

def countLetters(word):
    return len([x for x in word if x.isalpha()])

print(countLetters("Word."))
print(countLetters("Word.with.non-letters1"))

#Output:
4
18

This is equivalent to looping over all letters in a word and checking if each character is a letter.

def countLetters(word):
    count = 0
    for x in word:
        if x.isalpha():
            count = count + 1
    return count

print(countLetters("Word."))
print(countLetters("Word.with.non-letters1"))

#Output:
4
18

If you’d like to get the count of each letter in Python, you can use the Python collections module.

import collections

print(collections.Counter("Word"))

#Output:
Counter({'W': 1, 'o': 1, 'r': 1, 'd': 1})

If you’d like to get the letters of all words in a string, we can use the Python split() function in combination with the len() function.

string_of_words = "This is a string of words."

letter_counts = []
for x in string_of_words.split(" "):
    letter_counts.append(len([x for x in word if x.isalpha()]))

print(letter_counts)

#Output:
[4, 2, 1, 6, 2, 5]

When working with strings, it is very useful to be able to easily extract information about our variables.

One such piece of information which is valuable is the number of letters a string has.

We can use the Python len() function to get the number of letters in a string easily.

print(len("Word"))

#Output:
4

If you have a string with punctuation or numbers in it, we can use list comprehension to filter out the characters which aren’t letters and then get the length of this new string.

def countLetters(word):
    return len([x for x in word if x.isalpha()])

print(countLetters("Word."))
print(countLetters("Word.with.non-letters1"))

#Output:
4
18

If you don’t want to use list comprehension, loop over each element in the string and see if it is a letter or not with the Python isalpha() function.

def countLetters(word):
    count = 0
    for x in word:
        if x.isalpha():
            count = count + 1
    return count

print(countLetters("Word."))
print(countLetters("Word.with.non-letters1"))

#Output:
4
18

Finding Count of All Letters in a Word Using Python

In Python, we can also find the unique count of all letters in a word, and the number of times each letter appears in a word.

The Python collections module is very useful and provides a number of functions which allow us to create new data structures from lists.

One such data structure is the Counter data structure.

The Counter data structure counts up all of the occurrences of a value in a list.

To get the count of all letters in a word, we can use the Python collections Counter data structure in the following Python code.

import collections

print(collections.Counter("Word"))

#Output:
Counter({'W': 1, 'o': 1, 'r': 1, 'd': 1})

If you then want to get the count of any particular letter, you can access the count just like you would access a value in a dictionary.

import collections

c = collections.Counter("Word")

print(c["W"])

#Output:
1

Counting Letters of All Words in a String Using Python

When processing strings in a program, it can be useful to know how many words there are in the string, and how many letters are in each word. Using Python, we can easily get the number of letters in each word in a string with the Python len() function.

Let’s say you have a string which is a sentence (in other words, each word in the sentence is delimited by a space).

We can use the Python split() function to change the string into a list, and then loop over the list to get the length of each word in a string.

Below is a Python function which will count the letters in all words in a string using Python.

string_of_words = "This is a string of words."

letter_counts = []
for x in string_of_words.split(" "):
    letter_counts.append(len([x for x in word if x.isalpha()]))

print(letter_counts)

#Output:
[4, 2, 1, 6, 2, 5]

Hopefully this article has been useful for you to learn how to count letters in words in Python.

Other Articles You'll Also Like:

  • 1.  Remove Brackets from String Using Python
  • 2.  Using Python to Add String to List
  • 3.  Python getsizeof() Function – Get Size of Object
  • 4.  Divide Each Element in List by Scalar Value with Python
  • 5.  Get Size of File in Python with os.path.getsize() Function
  • 6.  How to Get the Size of a List in Python Using len() Function
  • 7.  Check if String Contains Only Certain Characters in Python
  • 8.  Remove All Instances of Value from List in Python
  • 9.  Write Variable to File Using Python
  • 10.  Convert String into Tuple in Python

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

About The Programming Expert

the programming expert main image

Welcome to The Programming Expert. We are a group of US-based programming professionals who have helped companies build, maintain, and improve everything from simple websites to large-scale projects.

We built The Programming Expert to help you solve your programming problems with useful coding methods and functions in various programming languages.

Search

Learn Coding from Experts on Udemy

Looking to boost your skills and learn how to become a programming expert?

Check out the links below to view Udemy courses for learning to program in the following languages:

Copyright © 2023 · The Programming Expert · About · Privacy Policy