python - Python 版本无关的字符串处理
问题描述
我对字符串与字节数组的区别很好。Python3 区分字符串和字节,python2 不太清楚。美好的。考虑这两行代码:
a=b'AAA' #a bytes array seen from Python3, a string/bytes for python2
b='BBB' #a string for python3, a string/bytes for python2
我想写一些代码转换和,在这里,连接两者a
并b
返回一个字节/字符串(在python2中)或字节数组(在python3中)。(预期结果beeing - 视为ASCII char- AAABBB)
换句话说,我想要一个与 python 版本无关的行,相当于:
result = a+b #returns a string/bytes in python2
和
result = a+bytes(b,'utf-8') #returns a bytes array in python3
我希望这行代码可以在 python 2 和 3 上运行(无需更改)并避免花哨的非标准包(结构可以),因为它可以在嵌入式系统上运行。
如果您想知道哪种编码,我最好的选择是最接近 8 位扩展 ASCII 表的编码(256 个值:我可能有反斜杠或欧洲字符,但没有中文)
到目前为止我发现的最好的是: result = a + b.encode('ASCII')
这是 ASCII 字符 >127 的问题。我尝试使用'cp437',但无论如何它似乎默认为ascii ...
@martineau 提出的尝试:
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a=b'aaa'
>>> b='bbbä'
>>> a+b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't concat str to bytes
>>> a+bytes(b,'latin1')
b'aaabbb\xe4'
Python 2.7.15rc1 (default, Nov 12 2018, 14:31:15)
[GCC 7.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a=b'aaa'
>>> b='bbbä'
>>> a+b
'aaabbb\xc3\xa4'
>>> a+bytes(b,'latin1')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: str() takes at most 1 argument (2 given)
解决方案
我建议看一下six
,一个专门设计用于处理 Python 2 和 Python 3 之间(某些)差异的 Python 模块。特别是,函数ensure_binary
(参见https://six.readthedocs.io/#six.ensure_binary)可以解决您的问题问题。
请注意,我了解您希望避免依赖“花哨的第三方库”,但six
不是“花哨的”;)但是,我不知道嵌入式系统的开销可能是什么。
推荐阅读
- java - Java:循环等待,直到 ThreadPoolExecutor 的任务完成后再继续
- php - 未找到 Laravel 自定义作曲家 libaray 类
- tags - 如何在 Runner 类中对 Cucumber 标签进行排序
- python - 在方法中调用函数
- android - 带有 XML 的 BottomNavigationView 设计 *没有以编程方式
- excel - 如何在 VBA 中打开具有可变日期名称的文件?
- twilio - 入站 Twllio SMS 触发 LogicApp
- botframework - 有没有办法从 Stack Overflow 中提取共享相同标签的问题和答案?
- azure - 我可以通过设备令牌获取注册吗?
- javascript - 使用异步等待获取失败时如何捕获状态代码