Python 2 vs 3:从字节串获取字节的一致结果

问题描述 投票:2回答:3

是否有任何简单的方法可以在Python 2和Python 3中获得一致的结果以进行操作,例如“在字节字符串中给我第N个字节”?只要保持一致,就可以获取整数字节或字符字节。

即给定

s = b"123"

朴素的方法产生:

s[1] # => Python 2: '2', <type 'str'>
s[1] # => Python 3: 50, <class 'int'>

ord(...)中包装在Python 3中产生错误:

ord(s[1]) # => Python 2: 50, <type 'int'> 
ord(s[1]) # => Python 3: TypeError: ord() expected string of length 1, but int found

我可以想到一个相当复杂的兼容解决方案:

ord(s[1]) if (type(s[1]) == type("str")) else s[1] # 50 in both Python 2 and 3

...但是也许有一种更简单的方法,我只是没有注意到?

python python-3.x python-2.x
3个回答
2
投票

长度为1的切片在2.x或3.x中也将是字节序列:

s = b'123'
s[1:2] # 3.x: b'2'; 2.x: '2', which is the same thing but the repr() rules are different.

1
投票

如果使用(如果需要,可以进行转换)bytearray类型,则两个版本的行为都相同,始终匹配bytes的Python 3行为。这是因为bytearray实际上是Python 2(具有Python 3行为)上的独特类型,其中bytes只是那里的str的别名。

更典型的解决方案是使用提供sixsix.indexbytes兼容性库,因此在任一版本的Python上,您都可以这样做:

six.indexbytes

0
投票

类似的东西呢?

>>> six.indexbytes(s, 1)
50

-1
投票

import sys if sys.version_info.major == 3: def index(s, n): return s[n] elif sys.version_info.major == 2: def index(s, n): return ord(s[n]) else: raise NotImplementedError 前缀字符串,您将在Python版本之间保持一致。

u
© www.soinside.com 2019 - 2024. All rights reserved.