gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:13:09 25 4
gpt4 key购买 nike

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

有没有办法在字符串上使用“掩码”?也就是

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

简单地重复搜索是没有选择的,因为这太耗费 CPU。

更新

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

最佳答案

str.find 接受关于从哪里开始/结束搜索的选项参数,例如:

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

来自文档:

find(...)

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.

关于python - 我可以在 Python 中搜索一段字符串但保持索引相对于原始字符串吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38346667/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com