
- 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 – 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.
- Related Articles
- Python program – All occurrences of Substring from the list of strings
- Replace All Occurrences of a Python Substring with a New String?
- Python - Find all the strings that are substrings to the given list of strings
- 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?
- Extract numbers from list of strings in Python
- Python Program to Find Number of Occurrences of All Elements in a Linked List
- How to remove empty strings from a list of strings in Python?
- Duplicate substring removal from list in Python
- Python – Strings with all given List characters
- Return a copy of the string with all occurrences of substring old replaced by new in Numpy
- Maximum Number of Occurrences of a Substring in C++
- Count occurrences of a substring recursively in Java
- Python Program – Strings with all given List characters
- Converting all strings in list to integers in Python

Advertisements