
Problem Formulation
- Given a string
s
, and - Given a character
c
.
How many times does character c
occur in the string s
?
Consider the following examples:
INPUT s = 'hello world' c = 'l' OUTPUT 3 INPUT s = 'aaaa' c = 'a' OUTPUT 4 INPUT s = 'finxter' c = 'z' OUTPUT 0
Method 1: str.count()
Python’s str.count(sub)
method counts the number of non-overlapping occurrences of a substring. If you pass a substring with only one character, it counts the number of occurrences of this character in the string on which it is called.
Here’s how you can apply this method to the three examples from the problem formulation:
>>> 'hello world'.count('l') 3 >>> 'aaaa'.count('a') 4 >>> 'finxter'.count('z') 0
You can watch the following video introducing the count()
method of Python strings:
Method 2: Regular Expression
Python’s re.findall(pattern, string)
determines the number of matches of a given pattern in a string. Use a simple one-character pattern to find all matches of this character in a string. The result is a list of matches—the length of the list is the number of occurrences of the character in the string leading to the solution method len(re.findall(c, s))
.
Here’s how you can apply this method to the three examples from the problem formulation:
>>> import re >>> len(re.findall('l', 'hello world')) 3 >>> len(re.findall('a', 'aaaa')) 4 >>> len(re.findall('z', 'finxter')) 0
Method 3: List Comprehension + len()
The list comprehension expression len([x for x in s if x == c])
determines an iterable of characters from s
that are equal to c
. By passing it into the len()
function, you obtain the number of occurrences of c
in s
.
Here’s how you can apply this method to the three examples from the problem formulation:
>>> len([x for x in 'hello world' if x == 'l']) 3 >>> len([x for x in 'aaaa' if x == 'a']) 4 >>> len([x for x in 'finxter' if x == 'z']) 0

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.