

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 Questions & Answers
- Python program – All occurrences of Substring from the list of strings
- 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
- Extract numbers from list of strings in Python
- How can we replace all the occurrences of a substring with another substring within a string in MySQL?
- Python Program to Find Number of Occurrences of All Elements in a Linked List
- Maximum Number of Occurrences of a Substring in C++
- Return a copy of the string with all occurrences of substring old replaced by new in Numpy
- Count occurrences of a substring recursively in Java
- How to remove empty strings from a list of strings in Python?
- Duplicate substring removal from list in Python
- Convert list of strings to list of tuples in Python
- Convert list of tuples to list of strings in Python
- Python program to find the character position of Kth word from a list of strings
- Python – Strings with all given List characters
Advertisements