python3中的波斯语或阿拉伯语的unicode和编码

时间:2014-03-20 18:58:43

标签: python python-3.x unicode

这样的一些代码:

city_name = obj['city_from']['name'].encode('utf-8')
            print(city_name)

此代码的输出为:

b'\xd8\xa8\xd9\x86\xd8\xaf\xd8\xb1\xd8\xb9\xd8\xa8\xd8\xa7\xd8\xb3'

如果我删除encode('utf-8')输出更改,如下所示:

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-7: ordinal not in range(128)

这个输出语言是波斯语(像阿拉伯语),我想知道为什么python3中的字符串类没有任何解码方法? 你有解决这个问题的方法吗?

谢谢

2 个答案:

答案 0 :(得分:2)

Your answer shows that your terminal accepts utf-8 byte sequences

在打印之前,您不需要将Unicode字符串转换为字节。 Python为你做到了。

更改Python用于I / O的字符编码;设置PYTHONIOENCODING=utf-8环境变量或更改您的区域设置。

在您的案例中,sys.stdout.encoding似乎是ascii

$ python3 -c'import sys; print(sys.stdout.encoding)' 
UTF-8
$ python3 -c'import sys; print(sys.stdout.encoding)' | cat
ascii
$ LC_CTYPE=C python3 -c'import sys; print(sys.stdout.encoding)' 
ANSI_X3.4-1968

ANSI_X3.4-1968ascii的规范名称。

$ PYTHONIOENCODING=uTf-8 python3 -c'import sys; print(sys.stdout.encoding)' | cat
uTf-8
$ LC_CTYPE=C.UTF-8 python3 -c'import sys; print(sys.stdout.encoding)' 
UTF-8

不要对脚本中的字符编码进行硬编码。打印Unicode字符串并相应地配置您的环境

答案 1 :(得分:0)

我发现了我的解决方案,它就像一个魅力

import sys
sys.stdout.buffer.write(TestText2)

更新: 这个问题对于ZSH脚本环境,我使用bash,一切都找到了。