【问题标题】:Python - Print readable format from String containing \n and other unicodes?Python - 从包含 \n 和其他 unicode 的字符串打印可读格式?
【发布时间】:2018-10-18 20:15:53
【问题描述】:

这个消息最初是一个集合,然后我用 str(a) 转换成字符串

a = "Let\u2019s trade!\n\u00a0\n\nAn Old Friendship, A New Day!\nHere comes the old, visiting at your home.\nIt comes with a new story, about how to live the present, about how in his past he did wrong.\n\nThe new day shines andx2"

由于某种原因,当我打印它时

print(a)

它保留所有的 \n 和 \u2019s 并且不会将其格式化为新行或将 \u2019 格式化为 " ' " 右引号.. 所以它只是以纯文本形式显示

Let\u2019s trade!\n\u00a0\n\nAn Old Friendship, A New Day!\nHere comes the old, visiting at your home.\nIt comes with a new story, about how to live the present, about how in his past he did wrong.\n\nThe new day shines andx2

通常如果我这样做

print("Let\u2019s trade!\n\u00a0\n\nAn Old Friendship, A New Day!\nHere comes the old, visiting at your home.\nIt comes with a new story, about how to live the present, about how in his past he did wrong.\n\nThe new day shines andx2")

它会输出为

Let’s trade!
 

An Old Friendship, A New Day!
Here comes the old, visiting at your home.
It comes with a new story, about how to live the present, about how in his 
past he did wrong.

The new day shines and

我该如何解决这个问题?

【问题讨论】:

  • 很好奇,我希望您的第一个代码能够按照您想要的方式打印。你在什么样的环境中工作?命令行,IDE,还有什么?你能提供你的输出截图吗?
  • 我无法重现,使用 print(a)a 定义为您在 repl.it/languages/python3 上运行良好

标签: python string format readable


【解决方案1】:

我认为您可能会将初始对象转换为 __repr__ 而不是 __str__

差异看起来就像您正在经历的那样:

Python 3.6.5 (default, Mar 30 2018, 06:41:53)
>>> a = "Let\u2019s trade!\n\u00a0\n\nAn Old Friendship, A New Day!\nHere comes the old, visiting at your home.\nIt comes with a new story, about how to live the present, about how in his past he did wrong.\n\nThe new day shines andx2"
>>> print(a)
Let’s trade!


An Old Friendship, A New Day!
Here comes the old, visiting at your home.
It comes with a new story, about how to live the present, about how in 
his past he did wrong.

The new day shines andx2
>>> a_repr = repr(a)
>>> a_repr
"'Let’s trade!\\n\\xa0\\n\\nAn Old Friendship, A New Day!\\nHere comes the old, visiting at your home.\\nIt comes with a new story, about how to live the present, about how in his past he did wrong.\\n\\nThe new day shines andx2'"
>>> print(a_repr)
'Let’s trade!\n\xa0\n\nAn Old Friendship, A New Day!\nHere comes the old, visiting at your home.\nIt comes with a new story, about how to live the present, about how in his past he did wrong.\n\nThe new day shines andx2'

我会调查你是如何得到这个字符串的,并确保底层调用是str,而不是repr

【讨论】:

    猜你喜欢
    • 2021-06-17
    • 2019-05-01
    • 2010-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    • 1970-01-01
    相关资源
    最近更新 更多