When it is required to fetch all the occurrences of a substring from a list of strings, a list comprehension and the ‘startswith’ method is used.
Example
Below is a demonstration of the same −
my_string = "Python learn code test fun amazing object oriented"
sub_string = "object"
print("The string is : " )
print(my_string)
print("The sub-string is : " )
print(sub_string)
my_result = [index for index in range(len(my_string)) if my_string.startswith(sub_string, index)]
print("The resultant string is : ")
print(my_result)Output
The string is : Python learn code test fun amazing object oriented The sub-string is : object The resultant string is : [35]
Explanation
A string is defined and is displayed on the console.
A sub string is defined and is displayed on the console.
A list comprehension is used to iterate over the string and check if the string starts with a specific value.
This is done using the ‘startswith’ method.
This is assigned to a result.
This is displayed as output on the console.