Python 3 打印utf-8 编码字符串问题

标签 python python-3.x

我正在从网络服务请求一个字符串。当我从程序中打印它时:

variable = getFromNetwork()
print(variable)
我使用 python3 net.py 执行它我得到:
\xd8\xaa\xd9\x85\xd9\x84\xd9\x8a612
当我在 python3 CLI 中执行时:
>>> print("\xd8\xaa\xd9\x85\xd9\x84\xd9\x8a612")
تÙ
Ù
Ù612
Buy 当我在 python2 CLI 中执行时,我得到了正确的结果:
>>> print("\xd8\xaa\xd9\x85\xd9\x84\xd9\x8a612")
تملي612
我如何通过python3在我的程序中打印这个?
编辑
执行以下行后:
print(print(type(variable), repr(variable)))
得到了
<class 'str'> '\\xd8\\xaa\\xd9\\x85\\xd9\\x84\\xd9\\x8a612'
我想我应该先删除\\x使其成为十六进制然后解码。你的解决方案是什么!?

最佳答案

您需要指定编码,以便解释器知道如何解释数据:

s = "\xd8\xaa\xd9\x85\xd9\x84\xd9\x8a612"
y = s.encode('raw_unicode_escape')
print (y)  # is a bytes object now!
print (y.decode('utf-8'))
出去:
b'\xd8\xaa\xd9\x85\xd9\x84\xd9\x8a612'
تملي612

关于Python 3 打印utf-8 编码字符串问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62992137/

相关文章:

python - 存储空间数组 SQLite3

python正则表达式后缀匹配

python - 特定累积变化后的变化值

python - Spyder (Python 3.7) 启动时出现一个黑色窗口。我该如何修复它?

python-3.x - 操作系统错误 : [WinError 10049] The requested address is not valid in its context

mysql - ImportError:没有使用Python3的名为mysql.connector的模块?

python - 在 Jupyter 中停止 ipdb 调试

python - 如何标准化时间序列数据?

Python TIC TAC TOE 跳轮

python - 如何按名称取消异步任务?