'Start and End Position of symbols in a string
I am trying to find the start and end position of _ in a string as list of tuples.
The code I used is
sentence = 'special events _______ ______ ___ _______ ____ _____ _______ ___________ brochure subscriptions ticket guide'
symbol = '_'
position = [(match.start(),match.end()) for match in re.finditer(symbol, sentence)]
For this the output obtained is
[(15, 16), (16, 17), (17, 18), (18, 19), (19, 20)..................]
How to get the start and end position of continuous located symbols as a list of tuple.
Solution 1:[1]
You can do this:
sentence2 = ' ' + sentence[:-1]
starts = [i for i in range(len(sentence))if sentence[i] == '_' and sentence2[i] != '_' ]
ends = [i - 1 for i in range(len(sentence)) if sentence2[i] == '_' and sentence[i] != '_']
pairs = list(zip(starts, ends))
print(pairs)
Output:
[(15, 21), (23, 28), (30, 32), (34, 40), (42, 45), (47, 51), (53, 59), (61, 71)]
This will give the index of the first and last instances of symbol in a substring of one or more contiguous symbol characters. If you need results that use python slice semantics (start == index of first instance of symbol in a contiguous substring, end == index immediately following the last instance of symbol in that substring), you can change i - 1 to i in the initialization line for ends.
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 |
