The function:
def findOccurrences(s, ch):
return [i for i, letter in enumerate(s) if letter == ch]
findOccurrences(yourString, '|')
will return a list of the indices of yourString in which the | occur.
The function:
def findOccurrences(s, ch):
return [i for i, letter in enumerate(s) if letter == ch]
findOccurrences(yourString, '|')
will return a list of the indices of yourString in which the | occur.
if you want index of all occurrences of | character in a string you can do this
import re
example_string = "aaaaaa|bbbbbb|ccccc|dddd"
indexes = [x.start() for x in re.finditer('\|', example_string)]
print(indexes) # <-- [6, 13, 19]
also you can do
indexes = [x for x, v in enumerate(str) if v == '|']
print(indexes) # <-- [6, 13, 19]
python - Find all occurrences of a character in a String - Stack Overflow
python - How to find all occurrences of a substring? - Stack Overflow
Find all the occurrences of a character in a given list of string in python language - Stack Overflow
HELP - counting occurrences of all substrings within a list of strings.
Videos
I'd like to find all occurrences of a substring while ignore some characters. How can I do it in Python?
Example:
long_string = 'this is a t`es"t. Does the test work?' small_string = "test" chars_to_ignore = ['"', '`'] print(find_occurrences(long_string, small_string))
should return [(10, 16), (27, 31)] because we want to ignore the presence of chars ` and ".
-
(10, 16)is the start and end index of t`es"t inlong_string, -
(27, 31)is the start and end index oftestinlong_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]
I would maintain a second list of Booleans indicating which letters have been correctly matched.
>>> word_to_guess = "thicket"
>>> matched = [False for c in word_to_guess]
>>> for guess in "te":
... matched = [m or (guess == c) for m, c in zip(matched, word_to_guess)]
... print(list(zip(matched, word_to_guess)))
...
[(True, 't'), (False, 'h'), (False, 'i'), (False, 'c'), (False, 'k'), (False, 'e'), (True, 't')]
[(True, 't'), (False, 'h'), (False, 'i'), (False, 'c'), (False, 'k'), (True, 'e'), (True, 't')]