Python 2.7 中如何解决 unicode 和 str 转换的问题?

我现在有一个 str 类型的字符串: '\u54c8\u55bd'

现在想把它转换成:u'\u54c8\u55bd'

在不使用 eval/exec 的情况下,求教各位大神,我该怎么弄?

我试了一下,unicode('\u54c8\u55bd').replace('\\\\','\\')是不行的


Python 2.7 中如何解决 unicode 和 str 转换的问题?
3 回复

在Python 2.7里处理unicode和str确实是个坑。核心就记住一点:str是字节串,unicode才是真正的字符串。乱码问题基本都是这俩混用导致的。

关键原则:尽早解码,晚点编码。 数据进来就马上用.decode('utf-8')转成unicode,内部处理全用unicode,最后输出时再用.encode('utf-8')转回str。

# -*- coding: utf-8 -*-
# 1. 输入时解码
input_str = '你好世界'  # 这是个str(字节串)
unicode_str = input_str.decode('utf-8')  # 转成unicode

# 2. 内部处理全用unicode
processed = unicode_str + u'!'

# 3. 输出时编码
output_str = processed.encode('utf-8')
print output_str  # 输出:你好世界!

# 处理文件时指定编码
import codecs
with codecs.open('file.txt', 'r', 'utf-8') as f:
    content = f.read()  # 直接得到unicode

如果遇到UnicodeDecodeErrorUnicodeEncodeError,别用ignorereplace糊弄过去,先检查源数据的正确编码。实在不行就用chardet库检测编码:

import chardet
raw_data = '一些乱码数据'
encoding = chardet.detect(raw_data)['encoding']
if encoding:
    unicode_str = raw_data.decode(encoding)

还有个常见坑是字符串拼接,确保两边都是同类型:

# 错误示例
str1 = 'hello'
unicode1 = u'世界'
# result = str1 + unicode1  # 会报UnicodeDecodeError!

# 正确做法
result = str1.decode('utf-8') + unicode1
# 或者
result = str1 + unicode1.encode('utf-8')

总之,在Python 2.7里处理文本就得时刻清楚自己手里拿的是字节还是字符。

建议:升级到Python 3能彻底解决这个问题。


‘\u54c8\u55bd’.decode(‘unicode_escape’)

厉害厉害!

回到顶部