I m new to programming and came across a question If I have a string where I have 2 variables indexed.. and need the value from the middle.
for example, my string is HeyEveryoneImtryingtolearnpythonandihavequestion
where I have variables
V1 = 'Imtrying'
V2 = 'andihave'
what can I do to get the "learnpython" substring? or is it not valid?
CodePudding user response:
You can use index
and slicing:
s = 'HeyEveryoneImtryingtolearnpythonandihavequestion'
v1 = 'Imtrying'
v2 = 'andihave'
start = s.index(v1) len(v1)
end = s.index(v2, start)
output = s[start:end]
print(output) # tolearnpython
CodePudding user response:
You can also use regex:
import re
s = "HeyEveryoneImtryingtolearnpythonandihavequestion"
V1 = 'Imtryingto'
V2 = 'andihave'
a = re.search(f"{re.escape(V1)}(.*?){re.escape(V2)}", s).group(1) # 'learnpython'