A:
A substring pattern matching over a bounded number of bytes that matches characters that have the same value in that number of bytes is called a binary search. So, it's a search of the first N characters of a string for a prefix matching characters of length N.
The first matching character is the first character of the substring, the last matching character is the last character of the substring, and so on, because in string theory there is no smaller than the smallest element of an array.
This is exactly what you want to do with your example. The substring is the first three bytes (32 bits), the N is 8, and they should match.
EDIT: If you want to match the characters of the substring with the characters of the string, it's more accurate to say that you're looking for a binary search for a prefix, but this would make the search start where the substring ends, not where it begins, which is a bit unexpected and hard to find. I'm fairly sure that in the cases where you're looking for exactly N characters you don't need to use a substring match, but if you want a prefix match, here is how you could do it:
def find_substring(s, start, end):
length = len(s)
offset = (length - end) // 2 + start
while offset >= 0:
middle = offset
if s[middle] == s[-middle-1]:
offset = 0
break
else:
offset -= 1
return s[offset:end]
To go from a substring to a string (find from one substring to another one), you can use the str.join() method:
def find_substring(s, start, end):
length = len(s)
offset = (length - end) // 2 + start
while offset >= 0:
middle = offset
if s[middle] == s[-middle-1]: 01e38acffe
Related links:
Commentaires