Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I search a slice of a string in Python but keep the index relative to the original string?

I have a large string. I regularly have to search only parts of this string, but I do need to now where in the large string the bits found in the slices are found.

Is there a way to use a 'mask' on a string? That is

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

Simply repeating the search is no option as that is too CPU costly.

Update

The toy example above uses find. In practice I use re.finditer().

like image 344
Private Avatar asked Feb 07 '23 14:02

Private


1 Answers

str.find takes option arguments as to where to start/end the search, eg:

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

From the docs:

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.
like image 154
Jon Clements Avatar answered Feb 09 '23 07:02

Jon Clements