如何解码unicode字符串Python

may*_*yor 7 python string unicode encode decode

解码编码字符串的最佳方法是什么: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')
Run Code Online (Sandbox Code Playgroud)

但是,我一直得到同样的错误.

我已经阅读了关于unicode角色的内容,并尝试了一些来自SO的建议,但到目前为止还没有任何建议.我在这里错过了什么吗?

Sam*_*rji 9

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

像这样:

decoded_value = item.encode('utf-8')
Run Code Online (Sandbox Code Playgroud)