【问题标题】:In Python, how do I convert a list of ints and strings to Unicode?在 Python 中,如何将整数和字符串列表转换为 Unicode?
【发布时间】:2012-03-23 04:34:38
【问题描述】:
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!']

【问题讨论】:

  • 你想要的输出是什么? [u'Some strings', 1, 2, 3, u'More strings!'], [u'Some strings', u'1', u'2', u'3', u'More strings!'], [u'Some strings', u'More strings!'] ?

标签: python unicode


【解决方案1】:

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

【讨论】:

  • 这仅适用于 ASCII(decode() 是有目的的)。并将数字转换为unicode
  • 如果你通过-*- coding -*- pragmas 告诉 Python 解释器。还有 Unicode != U​​TF-8,对不起。
  • @Boldewyn 您可以将encoding 参数传递给unicode 函数,它的作用与.decode 完全相同
  • 是的,这是真的。我忘了这件事。但是您应该将其包含在答案中。
  • @jterrace:非常正确,它与.decode() 相同,即使它不再适用于整数。
【解决方案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!']

【讨论】:

  • 您也可以使用循环和 try/catch 块来执行此操作,但我认为这更整洁。
  • try/catch 块适用于具有解码方法但不是基本字符串实例的对象。它保留了动态语言的一个特性:您不必进行大量类型检查和花哨的继承。
  • 是的,它是简洁和使用动态哲学进行编程之间的折衷方案。我认为,如果可以提供帮助,您通常应该避免使用 try/catch 进行流量控制,但这两种解决方案都可能适合您的心态/情况。
  • 如何确保这对 Python 2/3 都是安全的?
猜你喜欢
  • 2012-03-22
  • 1970-01-01
  • 2014-06-29
  • 2013-09-08
  • 2010-11-02
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
相关资源
最近更新 更多