How to count the number of times a string appears in Python?

The count() method can be used to calculate the number of times a substring appears in a string. It takes a substring as a parameter and returns the number of times the substring appears in the string.

For example, counting the number of times the letter “p” appears in the string “apple”.

s = "apple"
count = s.count("p")
print(count)  # 输出: 2

Alternatively, if you want to count the occurrences of multiple substrings appearing at the same time in a string, you can achieve this by using a loop traversal method.

s = "apple"
substrings = ["p", "e"]
counts = [s.count(substring) for substring in substrings]
print(counts)  # 输出: [2, 2]

In this way, each element in the counts list represents the number of times the corresponding substring appears in the string.

广告
Closing in 10 seconds
bannerAds