Reputation: 7
I am trying to write a code in Python where I get a print out of all the words in between two keywords.
scenario = "This is a test to see if I can get Python to print out all the words in between Python and words"
go = False
start = "Python"
end = "words"
for line in scenario:
if start in line: go = True
elif end in line:
go = False
continue
if go: print(line)
Want to have a print out of "to print out all the"
Upvotes: 0
Views: 990
Reputation: 628
Split the string and go over it word by word to find the index at which the two keywords occur. Once you have those two indices, combine the list between those indices into a string.
scenario = 'This is a test to see if I can get Python to print out all the words in between Python and words'
start_word = 'Python'
end_word = 'words'
# Split the string into a list
list = scenario.split()
# Find start and end indices
start = list.index(start_word) + 1
end = list.index(end_word)
# Construct a string from elements at list indices between `start` and `end`
str = ' '.join(list[start : end])
# Print the result
print str
Upvotes: 0
Reputation: 3288
Slightly different approach, let's create a list which each element being a word in the sentence. Then let's use list.index()
to find which position in the sentence the start
and end
words first occur. We can then return the words in the list between those indices. We want it back as a string and not a list, so we join
them together with a space.
# list of words ['This', 'is', 'a', 'test', ...]
words = scenario.split()
# list of words between start and end ['to', 'print', ..., 'the']
matching_words = words[words.index(start)+1:words.index(end)]
# join back to one string with spaces between
' '.join(matching_words)
Result:
to print out all the
Upvotes: 2
Reputation: 7515
You can accomplish this with a simple regex
import re
txt = "This is a test to see if I can get Python to print out all the words in between Python and words"
x = re.search("(?<=Python\s).*?(?=\s+words)", txt)
Here is the regex in action --> REGEX101
Upvotes: 0
Reputation: 43300
Your initial problem is that you're iterating over scenario
the string, instead of splitting it into seperate words, (Use scenario.split()
) but then there are other issues about switching to searching for the end word once the start has been found, instead, you might like to use index to find the two strings and then slice the string
scenario = "This is a test to see if I can get Python to print out all the words in between Python and words"
start = "Python"
end = "words"
start_idx = scenario.index(start)
end_idx = scenario.index(end)
print(scenario[start_idx + len(start):end_idx].strip())
Upvotes: 0