python - 在 python 中编码/解码字符串

标签 python encoding

我有一个返回 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 格式?然后,您需要将字节序列(以 UTF-16 编码)从 string(字符串类型)显式解码为 Unicode 对象:

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

debug_string 也应该是 Unicode。

关于python - 在 python 中编码/解码字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8712082/

相关文章:

python - 如何在Python中创建多维数组typedef

python.data.ops.dataset_ops.BatchDataset - 如何使用它来创建训练和测试数据集

python - pyside QTextEdit 选定文本事件

python - 如何以与 python2 和 python3 一起使用的方式将 utf8 写入标准输出

php - 使用 json_encode() 时解析短数组语法时出错

powershell - PowerShell 的 UTF-8 输出

python - python中区分大小写的字符串匹配替换

python - 如何确定列中csv字段的长度并返回超过一定长度的所有内容

python - 如何使 scrapy 输出信息在 debian 中显示与在 Windows 中相同的 cjk 外观?

java - 解码密码或一些更复杂的方式来为用户发送密码?