Python String Count

Python String Count [A Short Tutorial]

Want to count how often a substring occurs in a string? Or how many lines a mult-line string has? Use the count method on any string object!

You can use a single argument (the substring to be counted), and two optional arguments start and end to indicate the first or the last index of the substring. This way, you can focus on a fixed area within your string.

Here is an example:

s = "Hi my name is, hi my name is, slim shady"

print(s.count("name"))
# 2

print(s.count("name", 10))
# 1


Leave a Comment