Pythong string help

wickid12

Regular Member
Joined
Dec 4, 2009
Messages
363
Reaction score
37
Does anyone know how to search between two parts in python in a string: like "hey there guy you" I would search for "hey " and "guy" and the result would be there.
 
it's hard to help with out knowing more.

what do you want it to return? the word between 'hey' and 'guy'? the words 'hey' and 'guy'? etc.
 
it would return "there".
 
this should get you started

Code:
string = "hey there guy you"

# convert string to list
strlst = string[0:].split(' ')

# convert string to dictionary 
strdict = dict(enumerate(string[0:].split(' ')))

# find position of words in strlst
for i in strdict:
	if strdict[i] == "hey":
		firstword = i + 1
	if strdict[i] == "guy":
		secondword = i

# here's your answer

answer = strlst[firstword:secondword]
print(answer)

you'll get some strange results if the string has the same word twice (ex: "do you know who you are talking to?")
 
Code:
import re
s = "hey there guy you hey there are no guy you"
result = re.findall(r"hey\s(.*?)\sguy", s)
#result == ["there", "there are no"]
 
Back
Top