Just learned Python 3 in 7 days, and I have the feeling that there's a bit of a hole in my understanding of byte strings. In Python 3, suppose I have a byte string b'1234'
. Its iterator returns integers:
Python 3.2.3 (default, May 26 2012, 18:49:27)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> for z in b'1234':
... print(type(z))
...
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
I can find an integer in the byte string (the definition of in
is that it searches for equality):
>>> 0x32 in b'1234'
True
However, I would like to find the index of a given integer in the byte string. bytes.index
requires a substring:
>>> b'1234'.index(b'2')
1
Now, if I have a variable x
that I want to find, this is the best I've come up with:
>>> x = 0x32
>>> b'1234'.index(bytes([x]))
1
I know Python is more elegant than that. I'm clearly missing something obvious. Any ideas as to a simpler way to do this other than creating a sequence of a single integer? Or is that really it?
Yes, that's the way to do it.
It's not much different from the way to search for a character in a string based on its code point:
x = 0x32
i ='1234'.index(chr(x))
>>>> bytearray(b'12345').index(0x32)
1
>>>> bytearray(b'12345').index(b'2')
1
>>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With