gpt4 book ai didi

python - 关于python unicode的困惑

转载 作者:太空宇宙 更新时间:2023-11-04 07:42:01 24 4
gpt4 key购买 nike

我在windows7下用sublime text写了一个python文件,文件里有一些汉字,所以运行的时候就认不出来了(cmd和git bash也一样):

# -*- coding: utf-8 -*- 
str = "测试"

print str

arr = []
arr.append(str)

print arr

结果是:

娴嬭瘯
['\xe6\xb5\x8b\xe8\xaf\x95']

我该如何解决这个问题?这个问题的原因是什么?并且 arr 打印结果不应该是像 \uXXX?

这样的 unicode

顺便说一下,如果没有 # -*- coding: utf-8 -*- 我什至无法运行它:

$ python test.py
File "test.py", line 2
SyntaxError: Non-ASCII character '\xe6' in file test.py on line 2, but no encodi
ng declared; see http://www.python.org/peps/pep-0263.html for details

刚才google了一下语句,为什么没有它代码就跑不起来了?

最佳答案

# -*- coding: utf-8 -*- 需要 specify the encoding在文件中使用。

你得到 ['\xe6\xb5\x8b\xe8\xaf\x95'] 作为输出,因为你的字符串是字节字符串而不是 unicode 字符串,添加一个 u 字符串前缀以将其转换为 unicode 字符串。

>>> strs = u"测试"
>>> lis = [strs]
>>> print lis
[u'\u6d4b\u8bd5']
>>> print lis[0]
测试

关于python - 关于python unicode的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18042186/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com