【问题标题】:Python convert unicode with ''.join (TypeError: sequence item 0: expected string, int found) [duplicate]Python使用''.join转换unicode(TypeError:序列项0:预期字符串,找到int)[重复]
【发布时间】:2016-10-12 08:40:55
【问题描述】:

我正在使用 python 2.7.9 将 unicode hex 转换为 unicode 文本,但我被以下代码卡住了:

text = '0421'
converted_text = ''.join([chr(int(''.join(c), 16)) for c in zip(text[0::4], text[1::4], text[2::4], text[3::4])])
print converted_text

ValueError: chr() arg not in range(256)

当我删除 chr() 时:

converted_text = ''.join([int(''.join(c), 16) for c in zip(text[0::4], text[1::4], text[2::4], text[3::4])])

TypeError: sequence item 0: expected string, int found

如果我尝试使用其他文本,例如“00DD”,它可以正常工作。 知道我的代码有什么问题吗?

【问题讨论】:

  • 尝试使用str(...) 而不是chr(...)
  • 实际上str(int(text, 16)) 给出了相同的结果。
  • 可以使用字符串方法.decode。在你的情况下,你会做text.decode('hex')
  • str() 没有帮助,导致 chr() 将十进制转换为格式为 '\x' 的 unicode 字符。
  • text.decode('hex') 解决了我的问题,在这种情况下我不需要' '.join(....)。谢谢!

标签: python unicode hex


【解决方案1】:

如果您需要 unicode 字符,那么解决方案是使用 unichr() 而不是 chr()。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-08
    • 1970-01-01
    • 2014-09-10
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多