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