
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python program – All occurrences of Substring from the list of strings
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.
- Related Articles
- Python – All occurrences of Substring from the list of strings
- Replace All Occurrences of a Python Substring with a New String?
- Python Program to Find Number of Occurrences of All Elements in a Linked List
- Python Program – Strings with all given List characters
- Python - Find all the strings that are substrings to the given list of strings
- Python program to find the character position of Kth word from a list of strings
- Program to find longest common prefix from list of strings in Python
- Return an array with the number of nonoverlapping occurrences of substring in Python
- How can we replace all the occurrences of a substring with another substring within a string in MySQL?
- Python program to sort strings by substring range
- Extract numbers from list of strings in Python
- How to remove empty strings from a list of strings in Python?
- Duplicate substring removal from list in Python
- Python Program to Replace all Occurrences of ‘a’ with $ in a String
- Python – Strings with all given List characters

Advertisements