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

时间:2012-03-05 17:30:09

标签: python unicode

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没有解码方法。

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

更新:

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

2 个答案:

答案 0 :(得分:11)

您可以使用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!']

UPDATE :既然您指定希望整数保持原样,我会使用它:

>>> 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')

答案 1 :(得分:11)

如果你想在整个字符串中保持整数,只需将字符串更改为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!']
相关问题