- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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.
Advertisements