'Python strings are missing a findall function analog to find [duplicate]
Python strings appear to be missing a function that returns the index of all matches.
There is a re.findall() in the Python module that supplies the power of regular expressions within the standard library. But using the re module to find all occurrences of one string in another seems excessive to me. There's no need for regular expressions in this case.
Solution 1:[1]
One solution is a custom findall() function to that finds all occurrences of a string. It is a mix of the methods of the re.findall() and the str.find() method and returns a list indexes where all the matches start.
from typing import Optional
def findall(
pattern: str, string: str, start: Optional[int] = None, end: Optional[int] = None
):
"""Find all matches of a pattern in a string.
Arguments
---------
pattern : str
The string to find.
string : str
The string to search in.
start : int or None
Where in the string to start the search for matches.
end : int or None
Where in the string to end the search for matches.
Returns
-------
list
A list of of the index of the start of all matches.
If no matches are found the list is empty.
"""
i = string.find(pattern, start, end)
if i == -1:
return []
else:
return [i] + findall(pattern, string, i + 1, end)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
