Finding multiple occurrences of a string within a string in Python
Using regular expressions, you can use re.finditer
to find all (non-overlapping) occurences:
>>> import re
>>> text = 'Allowed Hello Hollow'
>>> for m in re.finditer('ll', text):
print('ll found', m.start(), m.end())
ll found 1 3
ll found 10 12
ll found 16 18
Alternatively, if you don't want the overhead of regular expressions, you can also repeatedly use str.find
to get the next index:
>>> text = 'Allowed Hello Hollow'
>>> index = 0
>>> while index < len(text):
index = text.find('ll', index)
if index == -1:
break
print('ll found at', index)
index += 2 # +2 because len('ll') == 2
ll found at 1
ll found at 10
ll found at 16
This also works for lists and other sequences.
How to find all occurrences of a substring?
There is no simple built-in string function that does what you're looking for, but you could use the more powerful regular expressions:
import re
[m.start() for m in re.finditer('test', 'test test test test')]
#[0, 5, 10, 15]
If you want to find overlapping matches, lookahead will do that:
[m.start() for m in re.finditer('(?=tt)', 'ttt')]
#[0, 1]
If you want a reverse find-all without overlaps, you can combine positive and negative lookahead into an expression like this:
search = 'tt'
[m.start() for m in re.finditer('(?=%s)(?!.{1,%d}%s)' % (search, len(search)-1, search), 'ttt')]
#[1]
re.finditer
returns a generator, so you could change the []
in the above to ()
to get a generator instead of a list which will be more efficient if you're only iterating through the results once.
Check if multiple strings exist in another string
You can use any
:
a_string = "A string is more than its parts!"
matches = ["more", "wholesome", "milk"]
if any(x in a_string for x in matches):
Similarly to check if all the strings from the list are found, use all
instead of any
.
How do I check whether or not a substring appears multiple times within a list in Python?
You can use in
for each string in the list:
>>> player_hand = ['Ace of Spades', 'Nine of Diamonds', 'Ace of Diamonds']
>>> sum(1 for x in player_hand if 'Ace' in x)
2
This uses a generator expression to go through the list that gives you a 1
if Ace
is in a string of the list. Summing up the ones gives you the total count of strings that contain Ace
.
Find all occurrences of a character in a String
One way to do this is to find the indices using list comprehension:
currentWord = "hello"
guess = "l"
occurrences = currentWord.count(guess)
indices = [i for i, a in enumerate(currentWord) if a == guess]
print indices
output:
[2, 3]
Finding a string multiple times in another String - Python
You can do:
>>> haystack = "abcdefabc. asdli! ndsf acba saa abe?"
>>> needle = "abc"
>>> for i, _ in enumerate(haystack):
... if haystack[i:i + len(needle)] == needle:
... print (i)
...
0
6
find multiple string occurrences in Python
You could do:
if all( x in 'hello world' for x in ['hel','ell','orl'] ):
print "Found all of them"
The built-in functions all
and any
are useful for this kind of thing.
Related Topics
How to Find the Last Occurrence of an Item in a Python List
What Does -1 Mean in Numpy Reshape
How to Manually Install a Pypi Module Without Pip/Easy_Install
Remove Punctuation from Unicode Formatted Strings
Creating a New Column Based on If-Elif-Else Condition
How to Expand a List to Function Arguments in Python
How to Interpret Conda Package Conflicts
Converting Xml to JSON Using Python
How to Split and Parse a String in Python
Pandas Dataframe Str.Contains() and Operation
String Concatenation Without '+' Operator
Pandas: Converting to Numeric, Creating Nans When Necessary
Attributeerror: Module 'Time' Has No Attribute 'Clock' in Python 3.8