Python – All occurrences of Substring from the list of strings


When it is required to get all the occurrences of a substring from the list of strings, a simple list comprehension and the ‘startswith’ method is used.

Example

Below is a demonstration of the same −

my_string = "Is python fun to learn?"

print("The list is :")
print(my_string)

substring = "pyt"
print("The substring is :")
print(substring)

my_result = [i for i in range(len(my_string)) if my_string.startswith(substring, i)]

print("The result is :")
print(my_result)

Output

The list is :
Is python fun to learn?
The substring is :
pyt
The result is :
[3]

Explanation

  • A string is defined and is displayed on the console.

  • Another substring is defined and displayed on the console.

  • A list comprehension is used to iterate over the string.

  • The ‘startswith’ method is used to check if the string begins with a specific pattern/substring.

  • If yes, it is added to a variable after converting to a list.

  • This is displayed as output on the console.

Updated on: 08-Sep-2021

131 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements