Python 3 bytes.index: better way?

11,367

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))
Share:
11,367
Robert B
Author by

Robert B

Updated on June 12, 2022

Comments

  • Robert B
    Robert B almost 2 years

    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?