如何解码unicode字符串Python [英] How to decode a unicode string Python

查看:327
本文介绍了如何解码unicode字符串Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the best way to decode an encoded string that looks like: u'u\xf1somestring' ?

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

Background: I have a list that contains random values (strings and integers), I'm trying to convert every item in the list to a string then process each of them.

列出一些格式如下的项目: u'u\xf1somestring'
当我尝试转换为字符串时,得到错误: UnicodeEncodeError:'ascii'编解码器无法对位置1处的字符u'\xf1'进行编码:序数不在范围内(128)

Turns out some of the items are of the format: u'u\xf1somestring' When I tried converting to a string, I get the error: 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')

但是,我一直都一样错误。

However, I keep getting the same error.

我已经阅读了有关Unicode字符的信息,并尝试了SO中的许多建议,但到目前为止都没有奏效。我在这里想念什么吗?

I have read up about unicode characters and tried a number of suggestions from SO but none have worked so far. Am I missing something here?

推荐答案

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

You need to call encode function and not decode function, as item is already decoded.

就像这样:

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

这篇关于如何解码unicode字符串Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆