什么是通用字符串处理的最简单方法,它可以在 python2 和 python3 中工作,而无需使用像 six 这样的第三方模块? ?
我可以使用 if sys.version_info > (3, 0)...
但无法想出一种方法来干净地覆盖字符串方法以进行编码/解码和来自字节透明?
目标是找到允许编写独立的版本不可知脚本(没有依赖项)的最少可能代码。
最佳答案
six source code并不太复杂,为什么不将字符串部分复制到您的代码库中呢?这样你就有了一个完善的统一字符串处理方法。 IE。下面的代码应该做的:
import sys
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
if PY3:
text_type = str
binary_type = bytes
else:
text_type = unicode
binary_type = str
def ensure_binary(s, encoding='utf-8', errors='strict'):
if isinstance(s, text_type):
return s.encode(encoding, errors)
elif isinstance(s, binary_type):
return s
else:
raise TypeError("not expecting type '%s'" % type(s))
def ensure_str(s, encoding='utf-8', errors='strict'):
if not isinstance(s, (text_type, binary_type)):
raise TypeError("not expecting type '%s'" % type(s))
if PY2 and isinstance(s, text_type):
s = s.encode(encoding, errors)
elif PY3 and isinstance(s, binary_type):
s = s.decode(encoding, errors)
return s
def ensure_text(s, encoding='utf-8', errors='strict'):
if isinstance(s, binary_type):
return s.decode(encoding, errors)
elif isinstance(s, text_type):
return s
else:
raise TypeError("not expecting type '%s'" % type(s))
关于python - 如何在没有外部模块的情况下跨 pythons 2 和 3 透明地处理字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59293633/