Python是否从包含\n和其他Unicode的字符串打印可读格式?

2024-06-11 02:18:19 发布

您现在位置:Python中文网/ 问答频道 /正文

这个消息最初是一个集合,然后我用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和\u2019,不会将其格式化为新行或\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

我该怎么解决这个问题?你知道吗


Tags: thenewyouroldathowaboutlet
1条回答
网友
1楼 · 发布于 2024-06-11 02:18:19

我认为您可能正在将初始对象转换为__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。你知道吗

相关问题 更多 >