在Python中,如何将int和string列表转换为Unicode?

2024-09-25 16:32:52 发布

您现在位置:Python中文网/ 问答频道 /正文

x = ['Some strings.', 1, 2, 3, 'More strings!', 'Fanc\xc3\xbf string!']
y = [i.decode('UTF-8') for i in x]

将x中的字符串转换为Unicode的最佳方法是什么?执行列表压缩会导致属性错误(AttributeError: 'int' object has no attribute 'decode'),因为int没有decode方法。

我可以试试用for循环吗?或者我可以在列表压缩中做一些显式的类型检查,但是在Python这样的动态语言中进行类型检查是正确的方法吗?

更新:

我希望int仍然是int,尽管这不是一个严格的要求。我的理想输出是[u'Some strings.', 1, 2, 3, u'More strings!', u'Fancÿ string!']


Tags: 方法in类型列表forstringmoresome
2条回答

如果您想在将字符串更改为unicode时保留列表中的整数,可以

x = ['Some strings.', 1, 2, 3, 'More strings!']
y = [i.decode('UTF-8') if isinstance(i, basestring) else i for i in x]

这让你

[u'Some strings.', 1, 2, 3, u'More strings!']

您可以使用unicode函数:

>>> x = ['Some strings.', 1, 2, 3, 'More strings!']
>>> y = [unicode(i) for i in x]
>>> y
[u'Some strings.', u'1', u'2', u'3', u'More strings!']

更新:由于您指定希望整数保持原样,我将使用以下命令:

>>> y = [unicode(i) if isinstance(i, basestring) else i for i in x]
>>> y
[u'Some strings.', 1, 2, 3, u'More strings!']

注意:正如@Boldewyn指出的,如果您想要UTF-8,您应该将encoding参数传递给unicode函数:

unicode(i, encoding='UTF-8')

相关问题 更多 >