繁体   English   中英

在python中编码/解码字符串

[英]encoding/decoding strings in 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)

你知道可能的原因是什么吗?

谢谢

你的string变量不是Unicode? 然后,您需要从string (字符串类型)到Unicode对象显式解码字节序列(以UTF-16编码):

u_string = myfunc().decode('utf-16')

debug_string也应该是Unicode。

尝试:

string = myfunc()

debug_string = debug_string.replace("$rep$", string).encode('utf-16')

要么:

string = myfunc()

debug_string = debug_string.replace("$rep$", string).decode('utf-16')

如果可能的话,一直使用unicodes。 如果你不能改变myfunc ,至少将其结果转换为unicode:

string = myfunc().decode('utf-16')

如果您的debug_string已经是unicode,则无需更改任何其他内容。 否则使用适当的编解码器对其进行解码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM