The count String Method in Python: Counting Substring Occurrences

The count method returns the number of non-overlapping occurrences of a substring in a string.

count(sub[, start[, end]])

  • sub -- substring to count;
  • start=0 -- position to start counting;
  • end=None -- position to stop counting.
my_str = 'substring from strings'
my_str.count('string')  # 1
my_str.count('str')  # 2
my_str.count('str', 0, -1)  # 2
my_str.count('str', 0, -3)  # 1
my_str.count('str', 8)  # 1
my_str.count('str', 1, 5)  # 0
my_str.count('str', 1, 6)  # 1

Start and end positions work like slices: negative values are offsets from the end, and the end is excluded.