string - 如何解码 unicode 字符串 Python

标签 string python-2.7 unicode decode encode

<分区>

解码如下所示的编码字符串的最佳方法是什么:u'u\xf1somestring'

背景:我有一个包含随机值(字符串和整数)的列表,我试图将列表中的每个项目转换为一个字符串,然后处理每个项目。

原来有些项目的格式是:u'u\xf1somestring' 当我尝试转换为字符串时,出现错误:UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 1: ordinal not in range(128)

我试过了

item = u'u\xf1somestring'
decoded_value = item.decode('utf-8', 'ignore')

但是,我不断收到同样的错误。

我已经阅读了有关 unicode 字符的信息,并尝试了 SO 的一些建议,但到目前为止都没有奏效。我在这里错过了什么吗?

最佳答案

您需要调用encode 函数而不是decode 函数,因为item 已经解码。

像这样:

decoded_value = item.encode('utf-8')

关于string - 如何解码 unicode 字符串 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35083374/

相关文章:

mysql - SQL查询字符串按分隔符分割

java - 拆分公式字符串

c - 如何在 C 中将 128 位整数转换为十进制 ascii 字符串?

c++ - 将字符串变量输出到 HEX 格式的文本文件中

python - 无法在AWS lambda中使用gitpython

html - 在纯文本 div 中插入新行

python - Matplotlib 错误 : "figure includes Axes that are not compatible with tight_layout"

python-2.7 - python opencv HSV 测距仪创建轨迹栏

swift - 正则表达式 unicode 在 swift 中不起作用

c - 使用正则表达式以 UTF8 读写 C 中的文本文件