Python 3 bytes.index:更好的方法?

Rob*_*t B 7 python indexing byte bytestring python-3.x

刚刚在7天内学习了Python 3,我觉得我对字节字符串的理解有点漏洞.在Python 3中,假设我有一个字节字符串b'1234'.它的迭代器返回整数:

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'> 
Run Code Online (Sandbox Code Playgroud)

我可以在字节字符串中找到一个整数(定义in是它搜索相等):

>>> 0x32 in b'1234'
True
Run Code Online (Sandbox Code Playgroud)

但是,我想在字节字符串中找到给定整数的索引.bytes.index需要一个子字符串:

>>> b'1234'.index(b'2')
1
Run Code Online (Sandbox Code Playgroud)

现在,如果我有一个x我想要找到的变量,这是我提出的最好的变量:

>>> x = 0x32
>>> b'1234'.index(bytes([x]))
1
Run Code Online (Sandbox Code Playgroud)

我知道Python比这更优雅.我显然遗漏了一些明显的东西.除了创建单个整数的序列之外,有关更简单的方法吗?或者是真的吗?

Mar*_*ers 6

是的,这是做到这一点的方式.

它与根据代码点在字符串中搜索字符的方式没有太大区别:

x = 0x32
i ='1234'.index(chr(x))
Run Code Online (Sandbox Code Playgroud)