【问题标题】:How to return str representation of non- Ascii letters in python如何在python中返回非Ascii字母的str表示
【发布时间】:2017-11-22 16:13:44
【问题描述】:

我有一个代码 sn-p 可以将葡萄牙语文本与数字分开。代码是:

import re
def name():
    text = u'Obras de revisão e recuperação (45453000-7)'
    splits = text.split(u" (")
    return(str(splits[0].encode("utf8")))
name()

输出为:'Obras de revis\xc3\xa3o e recupera\xc3\xa7\xc3\xa3o'

但是当我写的时候

print(splits[0].encode("utf8"))

输出将是:Obras de revisão e recuperação,这是我想要的结果。

但它不适用于返回函数。我阅读了difference between __str__ and __repr__,但我仍然不知道如何通过函数内部的返回获得与__str__ 相同的输出。

【问题讨论】:

  • 你说它不起作用是什么意思?发生什么了 ?你预计会发生什么?
  • 只需将您的函数包装在print() 中。例如:print(name())

标签: string python-2.7 python-unicode representation


【解决方案1】:

你想多了。您使用unicode 文字来创建您的unicode 对象,然后您的splits 列表将包含unicode 对象:

In [4]: def name():
   ...:     text = u'Obras de revisão e recuperação (45453000-7)'
   ...:     splits = text.split(u" (")
   ...:     return splits
   ...:

In [5]: splits = name()

In [6]: splits
Out[6]: [u'Obras de revis\xe3o e recupera\xe7\xe3o', u'45453000-7)']

list 打印到屏幕上时,使用list 中包含的对象的__repr__。但是,如果你想要__str__,只需使用print

In [7]: for piece in splits:
   ...:     print(piece)
   ...:
Obras de revisão e recuperação
45453000-7)

注意,.encode 返回一个字节串,即一个常规的、非unicode Python 2 str。在它上面调用str本质上是身份函数,当你encode它时它已经是str了:

In [8]: splits[0].encode('utf8')
Out[8]: 'Obras de revis\xc3\xa3o e recupera\xc3\xa7\xc3\xa3o'

In [9]: str(splits[0].encode('utf8'))
Out[9]: 'Obras de revis\xc3\xa3o e recupera\xc3\xa7\xc3\xa3o'

你真的应该考虑使用 Python 3,它可以简化这一点。 Python 3 中的str 对应于Python 2 的unicode,Python 2 的str 对应于Python 3 的bytes 对象。

所以,澄清一下,你的 name 函数应该像这样工作:

In [16]: def name():
    ...:     text = u'Obras de revisão e recuperação (45453000-7)'
    ...:     splits = text.split(u" (")
    ...:     return splits[0]
    ...:

In [17]: print(name())
Obras de revisão e recuperação

【讨论】:

  • @mk_sch 我不明白问题出在哪里?从根本上说,你的问题是你在做print(splits[0].encode("utf8")) 而你永远不需要.encode 你的unicode 对象
  • @mk_sch 没问题。我继续并将其添加到我的答案中。
猜你喜欢
  • 2011-04-02
  • 1970-01-01
  • 2010-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-19
  • 1970-01-01
  • 2010-12-11
相关资源
最近更新 更多