[英]Python 2 vs 3: consistent results with getting a byte from byte string
是否有任何簡單的方法可以在 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
...但可能有一種我沒有注意到的更簡單的方法?
長度為 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.
這樣的事情呢?
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
如果您使用(根據需要進行轉換) bytearray
類型,則兩個版本的行為將相同,始終匹配 Python 3 行為。 這是因為bytearray
實際上是 Python 2 上的不同類型(具有 Python 3 行為),其中bytes
只是str
的別名。
更典型的解決方案是使用提供six.indexbytes
的six
兼容庫,因此在 Python 的任一版本上,您都可以這樣做:
>>> six.indexbytes(s, 1)
50
使用u
為您的字符串添加前綴,您將在 Python 版本之間獲得一致性。
# Python 2
>>> ord(u"123"[0])
49
# Python 3
>>> ord(u"123"[0])
49
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.