内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用
如何找到两个子字符串('123STRINGabc' -> 'STRING'
)之间的字符串?
我目前的方法是这样的:
>>> start = 'asdf=5;'
>>> end = '123jasd'
>>> s = 'asdf=5;iwantthis123jasd'
>>> print((s.split(start))[1].split(end)[0])
iwantthis
但是,这似乎是非常低效。什么是更好的方式来做这样的事情?
s = "123123STRINGabcabc"
def find_between( s, first, last ):
try:
start = s.index( first ) + len( first )
end = s.index( last, start )
return s[start:end]
except ValueError:
return ""
def find_between_r( s, first, last ):
try:
start = s.rindex( first ) + len( first )
end = s.rindex( last, start )
return s[start:end]
except ValueError:
return ""
print find_between( s, "123", "abc" )
print find_between_r( s, "123", "abc" )
得到:
123STRING
STRINGabc