【问题标题】:Python gives output 'u' character before displaying anything? [duplicate]Python在显示任何内容之前给出输出'u'字符? [复制]
【发布时间】:2015-02-22 20:31:25
【问题描述】:

我是 python 新手,在我的 python 控制台中显示一些奇怪的东西,同时将输出显示到屏幕上。

>>> macbeth_sentsence = gutenberg.sents('shakespeare-macbeth.txt');
>>> macbeth_sentsence
[[u'[', u'The', u'Tragedie', u'of', u'Macbeth', u'by', u'William', u'Shakespeare', u'1603', u']'], [u'Actus', u'Primus', u'.'], ...]

我不希望在我的输出屏幕中出现额外的 'u' 字符。

任何人都知道如何抑制它?与默认 python 设置有什么关系?


以下更新:适用于不了解我要解决的问题的人。

当我的Windows系统在Vbox中执行相同的命令时

我得到了这样的东西:

>>> macbeth_sentsence = gutenberg.sents('shakespeare-macbeth.txt');
    >>> macbeth_sentsence
    [['[', 'The', 'Tragedie', 'of', 'Macbeth', 'by', 'William', 'Shakespeare', '1603', ']'], ['Actus', 'Primus', '.'], ...]

我想在我的 Mac 机器上得到同样的结果;我必须对我的默认值进行什么调整才能获得像我在 Windows 中得到的结果。

PS: 来自此的答案:removing `u` character in python output 这个:Python ascii utf unicode 而这个:Python string prints as [u'String'] 不是我想要的。

【问题讨论】:

  • 这只是意味着它是一个 unicode 字符串。如果您实际使用print 打印字符串,您不会看到。
  • 这是一个unicode u ,你为什么要删除它们?
  • 您看到的是 repr() 表示,它为您提供了一种格式,可让您在新的 Python 会话中重现该值。总是有助于调试。
  • @PadraicCunningham 是的,我明白这一点,但为什么它只显示给我?我在其他同行屏幕上看不到这些东西,而只有我的。 @larsks~ 好的,是的,但是我该如何删除它们?与默认值有什么关系?
  • @MartijnPieters 很高兴知道这一点,但我现在没有调试,你能告诉我如何抑制它并仅在需要时使用它吗?

标签: python


【解决方案1】:

它只是表示一个 unicode 字符串。 看 Easiest way to remove unicode representations from a string in python 3?

【讨论】:

  • 您链接到的帖子与列表等容器中的 unicode 表示无关。
【解决方案2】:

它是一个Unicode字符串,你可以通过转换为ascii来删除它:

macbeth_sentence = [[i.encode() for i in j] for j in macbeth_sentence]

【讨论】:

  • 撤销了投票,但这并没有回答我的问题。如何使这种变化永久化。
  • 它是永久性的。尝试打印new,你会发现前面没有u。
  • 我认为OP的意思是如何在原始列表中做到这一点
  • @MalikBrahimi~ 永久我的意思是下次如果我写类似 {>>> macbeth_sentsence = gutenberg.sents('shakespeare-macbeth.txt'); >>> macbeth_sentsence} 我不必对 macbeth_sentsence 进行编码,但它应该是默认的,没有 u。
  • 现在 ikis 好用吗?我使用列表推导遍历整个嵌套列表,并将每个字符串编码为 ascii。
猜你喜欢
  • 1970-01-01
  • 2016-12-06
  • 2017-02-11
  • 2021-02-26
  • 1970-01-01
  • 2012-04-05
  • 2010-12-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多