我希望能够使用函数抓取字符串部分。这是一个例子:
def get_sec(s1,s2,first='{',last='}'):
start = s2.index(first)
end = -(len(s2) - s2.index(last)) + 1
a = "".join(s2.split(first + last))
b = s1[:start] + s1[end:]
print a
print b
if a == b:
return s1[start:end]
else:
print "The strings did not match up"
string = 'contentonemore'
finder = 'content{}more'
print get_sec(string,finder)
#'one'
所以这个例子有效......我的问题是我想要多个部分,而不仅仅是一个。所以我的函数需要能够适用于任意数量的部分,例如:
test_str = 'contwotentonemorethree'
test_find = 'con{}tent{}more{}'
print get_sec(test_str,test_find)
#['one','two','three']
关于如何使该函数适用于任意数量的替换,有什么想法吗?
最佳答案
您可能想使用标准 python regex图书馆
import re
a = re.search('con(.*)tent(.*)more(.*)','contwotentonemorethree')
print a.groups()
# ('two', 'one', 'three')
或者 print re.findall('con(.)tent(.)more(.*)','contwotentonemorethird') # [('二', '一', '三')]
编辑:
您可以使用转义字符串中的特殊字符
re.escape(str)
示例:
part1 = re.escape('con(')
part2 = re.escape('(tent')
print re.findall(part1 + '(.*)' + part2,'con(two)tent')
关于python - 在Python中查找特定的字符串部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17158676/