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!']
。
如果您想在将字符串更改为unicode时保留列表中的整数,可以
这让你
您可以使用unicode函数:
更新:由于您指定希望整数保持原样,我将使用以下命令:
注意:正如@Boldewyn指出的,如果您想要UTF-8,您应该将
encoding
参数传递给unicode函数:相关问题 更多 >
编程相关推荐