【问题标题】:Detect the type of strings检测字符串类型
【发布时间】:2019-04-16 14:06:29
【问题描述】:

我想创建一个 python 脚本,它使用可以写入文件的字节格式字符串。

所以问题是这样的:

packed_int = struct.pack('>I', 1234)
result = packed_int + data

这是问题所在:在 python 3 中,由于 str 和 bytes 之间的连接,这会出错。

所以我用下面的代码解决了这个问题:

data = data.encode('utf-8')
packed_int = struct.pack('>I', 1234)
result = packed_int + data

现在如果数据已经是字节格式,这将给出没有编码方法的错误。所以我这样做了:

if type(data) is not bytes:
    data = data.encode('utf-8')

最后一个问题是在 python 2 中最后一个 sn-p 不起作用。

如何在不检查 python 版本的情况下解决问题?

【问题讨论】:

  • Python 2 将在 8 个月后报废 (pythonclock.org) – 我不会编写新代码来针对它,除非您明确必须这样做。

标签: python-3.x string python-2.7


【解决方案1】:

您可以将hasattr 用于duck typing

if hasattr(data, 'encode'):
    data = data.encode('utf-8')

或者你做这样的事情,这就是six 兼容性库所做的:

import sys

PY3 = sys.version_info[0] == 3
binary_type = (bytes if PY3 else str)
text_type = (str if PY3 else unicode)

# ...

if isinstance(data, text_type):
    data = data.encode('utf-8')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-29
    • 2019-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-19
    相关资源
    最近更新 更多