字符串值解码utf-8

String value decode utf-8

我想将字符串值解码为utf-8。但它没有改变。 所以,这是我的代码:

self.textEdit_3.append(str(self.new_header).decode("utf-8") + "\n")

结果图片在这里:

原输出值为:

['matchkey', 'a', 'b', 'd', '안녕'] # 안녕 is Korean Language

我将使用 unicode 编码/解码的默认编码更改为 utf-8 而不是 ascii。在第一行我添加了这段代码:

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

为什么字符串值没有改变?

您可以像这样修复您的代码:

header = str(self.new_header).decode('string-escape').decode("utf-8")
self.textEdit_3.append(header + "\n")

您不需要 setdefaultencoding 行。


扩展:

原始值是一个包含字节串的列表:

>>> value = ['matchkey', 'a', 'b', 'd', '안녕']
>>> value
['matchkey', 'a', 'b', 'd', '\xec\x95\x88\xeb\x85\x95']

如果您使用 str 转换此列表,它将对所有列表元素使用 repr

>>> strvalue = str(value)
>>> strvalue
"['matchkey', 'a', 'b', 'd', '\xec\x95\x88\xeb\x85\x95']"

repr部分可以这样解码:

>>> strvalue = strvalue.decode('string-escape')
>>> strvalue
"['matchkey', 'a', 'b', 'd', '\xec\x95\x88\xeb\x85\x95']"

现在可以像这样将其解码为 un​​icode:

>>> univalue = strvalue.decode('utf-8')
>>> univalue
u"['matchkey', 'a', 'b', 'd', '\uc548\ub155']"
>>> print univalue
['matchkey', 'a', 'b', 'd', '안녕']

PS:

关于使用utf-8 bom读取文件的问题,请测试这个脚本:

# -*- coding: utf-8 -*-

import os, codecs, tempfile

text = u'a,b,d,안녕'
data = text.encode('utf-8-sig')

print 'text:', repr(text), len(text)
print 'data:', repr(data), len(data)

f, path = tempfile.mkstemp()
print 'write:', os.write(f, data)
os.close(f)

with codecs.open(path, 'r', encoding='utf-8-sig') as f:
    string = f.read()
    print 'read:', repr(string), len(string), string == text