简体   繁体   中英

Way to slice a string using 2 variable in python

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?

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

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM