简体   繁体   English

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

[英]Python - Print readable format from String containing \n and other unicodes?

this message was originally a set and then i converted into string with str(a) 此消息最初是一个集合,然后我用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"

and for some reason when I print it 由于某种原因,当我打印它时

print(a)

it keeps all the \\n and \’s and doesn't format it into a new line or \’ into " ' " right quotation mark.. so it just shows as this in plaintext 它保留所有\\ 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

normally if i do 如果我正常的话

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")

it will output it as 它将输出为

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

how do i fix this? 我该如何解决?

I think you might be converting your initial object to a __repr__ instead of a __str__ . 我认为您可能会将初始对象转换为__repr__而不是__str__

The difference looks like what you are experiencing: 区别看起来像您正在经历的:

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'

I'd look into how you are getting this string, and make sure the underlying call is str , not repr . 我将研究您如何获取此字符串,并确保基础调用是str ,而不是repr

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM