在Python中编码/解码字符串

3

我有一个返回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)

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

其他环境是什么?那个产生错误的代码是实际的代码吗? - ekhumoro
3个回答

2

你的 string 变量不是 Unicode 编码的吗?那么你需要显式地将字节序列(UTF-16 编码)从 string(字符串类型)解码为 Unicode 对象:

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

debug_string 也应该是 Unicode 编码。


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格式,那么不需要进行其他更改。否则,请使用适当的编解码器对其进行解码。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接