How to Count Characters in a String in Python?

In this tutorial, I will explain how to count characters in a string in Python. As a Python developer working on various projects, I came across a scenario where I needed to count characters in a string, This led me to explore more about this topic. I found five effective ways to accomplish this task and I will explain all the methods with suitable examples.

Count Characters in a String in Python

Python provides five effective ways to count characters in a string. Let us learn these methods.

Read How to Check if a String is Empty or NaN in Python?

1. Use the count() Method

The simplest way to count the occurrences of a character in a string is by using the Python built-in count() method. This method returns the number of non-overlapping occurrences of a substring in the string.

city = "San Francisco"
count_a = city.count('a')
print(f"The letter 'a' appears {count_a} times in 'San Francisco'.")

Output:

The letter 'a' appears 2 times in 'San Francisco'.

In the screenshot below you can see the executed example code with the output.

Count Characters in a String in Python

Check out How to Check if a String is an Integer or Float in Python?

2. Use a For Loop

If you prefer a more manual approach, you can use a for loop to iterate through the Python string and count the characters.

city = "New York"
count_y = 0
for char in city:
    if char == 'y':
        count_y += 1
print(f"The letter 'y' appears {count_y} times in 'New York'.")

Output:

The letter 'y' appears 0 times in 'New York'.

In the screenshot below you can see the executed example code with the output.

How to Count Characters in a String in Python

Read How to Check if a String Starts with a Specific Substring in Python?

3. Use the collections.Counter

Python’s collections module provides a Counter class that makes it easy to count the occurrences of each character in a string.

from collections import Counter

state = "California"
char_count = Counter(state)
print(f"The letter 'i' appears {char_count['i']} times in 'California'.")

Output:

The letter 'i' appears 2 times in 'California'.

In the screenshot below you can see the executed example code with the output.

Count Characters in a String in Python list comprehension

Check out How to Check if a String Ends with a Pattern in Python?

4. Use List Comprehension

List comprehension in Python offers a concise way to count characters in a string.

state = "Texas"
count_e = sum([1 for char in state if char == 'e'])
print(f"The letter 'e' appears {count_e} times in 'Texas'.")

Output:

The letter 'e' appears 1 times in 'Texas'.

In the screenshot below you can see the executed example code with the output.

Count Characters in a String in Python re

Read How to Check if a String is All Uppercase in Python?

5. Use Regular Expressions

For more complex string manipulation, you can use Python’s re module to count characters.

import re

state = "Florida"
count_o = len(re.findall('o', state))
print(f"The letter 'o' appears {count_o} times in 'Florida'.")

Check out How to Check if a String is ASCII in Python?

Handle Case Sensitivity

By default, all the methods above are case-sensitive. If you want to count characters in a case-insensitive manner, you can convert the Python string to lowercase or uppercase before counting.

city = "Los Angeles"
count_a = city.lower().count('a')
print(f"The letter 'a' appears {count_a} times in 'Los Angeles' (case-insensitive).")

Read How to Check if a String is a Boolean Value in Python?

Count All Characters

If you need to count the occurrence of each character in the Python string, you can combine the Counter class with a loop or use dictionary comprehension.

city = "Chicago"
char_count = Counter(city)

for char, count in char_count.items():
    print(f"The character '{char}' appears {count} times in 'Chicago'.")

Check out How to Check if a String is Base64 Encoded in Python?

Example: Analyze a Text File

Let’s say you have a text file with names of cities in the USA, and you want to count how many times each letter appears in the file.

from collections import Counter

def count_characters_in_file(filename):
    with open(filename, 'r') as file:
        text = file.read()
    char_count = Counter(text)
    return char_count

filename = 'usa_cities.txt'
char_count = count_characters_in_file(filename)

for char, count in char_count.items():
    print(f"The character '{char}' appears {count} times in the file.")

Check out How to Check if a String Begins with a Number in Python?

Conclusion

In this tutorial, I have helped you to learn how to count characters in a string in Python. I covered some methods such as using the count() method, a for loop, collections.Counter, list comprehension, and regular expressions. I also covered how to handle case sensitivity, count all characters, and real-time example.

You may read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.