我是編程新手,遇到了一個問題,如果我有一個字串,其中我有 2 個索引變數......并且需要中間的值。
例如,我的字串是HeyEveryoneImtryingtolearnpythonandihavequestion
我有變數的地方
V1 = 'Imtrying'
V2 = 'andihave'
我該怎么做才能獲得“learnpython”子字串?還是無效?
uj5u.com熱心網友回復:
您可以使用index和切片:
s = 'HeyEveryoneImtryingtolearnpythonandihavequestion'
v1 = 'Imtrying'
v2 = 'andihave'
start = s.index(v1) len(v1)
end = s.index(v2, start)
output = s[start:end]
print(output) # tolearnpython
uj5u.com熱心網友回復:
您還可以使用正則運算式:
import re
s = "HeyEveryoneImtryingtolearnpythonandihavequestion"
V1 = 'Imtryingto'
V2 = 'andihave'
a = re.search(f"{re.escape(V1)}(.*?){re.escape(V2)}", s).group(1) # 'learnpython'
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/399296.html
