Answer the question
In order to leave comments, you need to log in
How to find the index of a word in a string if they are repeated?
Line example:
TEXT = """
The Zen of Python, by Tim Peters
1. Beautiful is better than ugly.
2. Explicit is better than implicit.
3. Simple is better than complex.
4. Complex is better than complicated.
"""
TEXT_WORDS = [
('the', 1), ('zen', 5), ('of', 9), ('python', 12), ('by', 20),
('tim', 23), ('peters', 27), ('beautiful', 37), ('is', 47),
('better', 50), ('than', 57), ('ugly', 62), ('explicit', 71),
('is', 80), ('better', 83), ('than', 90), ('implicit', 95),
('simple', 108), ('is', 115), ('better', 118), ('than', 125),
('complex', 130), ('complex', 142), ('is', 150), ('better', 153),
('than', 160), ('complicated', 165),
]
TEXT_WORDS = []
for word in TEXT.split():
r = (word, TEXT.index(word))
TEXT_WORDS.append(r)
Answer the question
In order to leave comments, you need to log in
The second parameter of the index method allows you to specify from which position the search should start. Specify the last result + the length of the last word:
TEXT_WORDS = []
index = 0
for word in TEXT.split():
index = TEXT.index(word, index)
TEXT_WORDS.append((word, index))
index += len(word)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question