我如何找到两个子字符串('123STRINGabc' -> '字符串')之间的字符串?
我现在的方法是这样的:
>>> start = 'asdf=5;'
>>> end = '123jasd'
>>> s = 'asdf=5;iwantthis123jasd'
>>> print((s.split(start))[1].split(end)[0])
iwantthis
然而,这似乎非常低效且不符合python规则。有什么更好的方法来做这样的事情吗?
忘了说:
字符串可能不是以start和end开始和结束的。他们可能会有更多的字符之前和之后。
您可以简单地使用这段代码或复制下面的函数。全都整齐地排在一条线上。
def substring(whole, sub1, sub2):
return whole[whole.index(sub1) : whole.index(sub2)]
如果按照如下方式运行该函数。
print(substring("5+(5*2)+2", "(", "("))
你可能会得到这样的输出:
(5*2
而不是
5*2
如果您希望在输出的末尾有子字符串,代码必须如下所示。
return whole[whole.index(sub1) : whole.index(sub2) + 1]
但如果不希望子字符串在末尾,则+1必须在第一个值上。
return whole[whole.index(sub1) + 1 : whole.index(sub2)]
这是我之前在Daniweb中发布的代码片段:
# picking up piece of string between separators
# function using partition, like partition, but drops the separators
def between(left,right,s):
before,_,a = s.partition(left)
a,_,after = a.partition(right)
return before,a,after
s = "bla bla blaa <a>data</a> lsdjfasdjöf (important notice) 'Daniweb forum' tcha tcha tchaa"
print between('<a>','</a>',s)
print between('(',')',s)
print between("'","'",s)
""" Output:
('bla bla blaa ', 'data', " lsdjfasdj\xc3\xb6f (important notice) 'Daniweb forum' tcha tcha tchaa")
('bla bla blaa <a>data</a> lsdjfasdj\xc3\xb6f ', 'important notice', " 'Daniweb forum' tcha tcha tchaa")
('bla bla blaa <a>data</a> lsdjfasdj\xc3\xb6f (important notice) ', 'Daniweb forum', ' tcha tcha tchaa')
"""