Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3 bytes.index: better way?

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?

like image 322
Robert B Avatar asked Jun 06 '12 23:06

Robert B


2 Answers

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))
like image 194
Mark Byers Avatar answered Oct 07 '22 22:10

Mark Byers


>>>> bytearray(b'12345').index(0x32)
1
>>>> bytearray(b'12345').index(b'2')   
1
>>>> 
like image 28
Leroy Scandal Avatar answered Oct 07 '22 21:10

Leroy Scandal