How to find substring position in bytes in Python?

358 Views Asked by At

PHP:

$str = "абвгдежз";
$p = strpos($str, "г");
echo $str, "\n", $p;

result: 6

Python:

str = "абвгдежз"
p = str.find("г")
print(str); print(p)

result: 3

1

There are 1 best solutions below

4
Barmar On

PHP's strpos() is not multibyte-aware, so it's counting the bytes, not characters. To get the equivalent in Python you need to convert the strings to byte strings with .encode()

str = "абвгдежз"
search = "г"
p = str.encode().find(search.encode())
print(str)
print(p)