Python 3 bytes.index: best way?

Just learned Python 3 after 7 days, and I have the feeling that in my understanding of byte strings there is a little hole. 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 the integer in the byte string (the definition of in is that it is looking for equality):

 >>> 0x32 in b'1234' True 

However, I would like to find the index of the given integer in the byte string. bytes.index requires a substring:

 >>> b'1234'.index(b'2') 1 

Now, if I have the x variable that I want to find, this is the best I came up with:

 >>> x = 0x32 >>> b'1234'.index(bytes([x])) 1 

I know Python is more elegant. I am obviously missing something obvious. Any ideas on an easier way to do this other than creating a coherent whole? Or is it really so?

+7
source share
2 answers

Yes, this is the way to do it.

This is not much different from the way a character is searched in a string based on its code point:

 x = 0x32 i ='1234'.index(chr(x)) 
+5
source

Also, take a look at Mark Pilgrim Dive Into Python 3, Chapter 4. Lines , section 4.6. Strings versus bytes . This perfectly explains the problems with the old Python 2.x strings (which became the byte type in Python 3) and how the new Python 3 new line is fundamentally different.

0
source

All Articles