在Python中编码/解码字符串
我有一个函数,它返回一个用utf-16编码的字符串,我需要把这个结果放进另一个字符串里,用替换的方法:
string = myfunc()
debug_string = debug_string.replace("$rep$", string)
在我的Eclipse环境中,这个功能正常,但在另一个环境中却出现了错误:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe0' in position 23: ordinal not in range(128)
你知道可能是什么原因吗?
谢谢
3 个回答
0
试试:
string = myfunc()
debug_string = debug_string.replace("$rep$", string).encode('utf-16')
或者:
string = myfunc()
debug_string = debug_string.replace("$rep$", string).decode('utf-16')
0
如果可以的话,尽量一直使用Unicode格式。如果你不能修改myfunc
这个函数,至少要把它的结果转换成Unicode格式:
string = myfunc().decode('utf-16')
如果你的debug_string
已经是Unicode格式,那就不需要再做其他的修改了。否则,记得用合适的编码方式把它解码。
2
你的 string
变量不是用Unicode编码的吗?那你需要把这个 string
(字符串类型)里的字节序列(用UTF-16编码)明确地解码成Unicode对象:
u_string = myfunc().decode('utf-16')
debug_string
也应该是Unicode格式的。