我可以在Python中搜索一个字符串片段但是保持索引相对于原始字符串吗?

Pri*_*ate 3 python regex string standard-library

我有一个大字符串.我经常只搜索这个字符串的一部分,但我现在需要在大字符串中找到切片中找到的位.

有没有办法在字符串上使用'掩码'?那是

original = 'This is a mock-up large string'
a_slice = original[10:23]
a_slice.find('o')  
>>> 1 in a_slice; 11 in original
Run Code Online (Sandbox Code Playgroud)

简单地重复搜索是没有选择的,因为这太昂贵了.

更新

上面的玩具示例使用find.在实践中我使用re.finditer().

Jon*_*nts 6

str.find 获取有关开始/结束搜索的位置的选项参数,例如:

original = 'This is a mock-up large string'
o = original.find('o', 10, 23)
# 11
Run Code Online (Sandbox Code Playgroud)

来自文档:

找(...)

S.find(sub [,start [,end]]) -> int

Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end].  Optional
arguments start and end are interpreted as in slice notation.
Run Code Online (Sandbox Code Playgroud)