[英]In Python, how do I convert a list of ints and strings to 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!']
。
你可以使用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')
如果你想保持列表中的整数,只需将字符串更改为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!']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.