xvienxz2
xvienxz2

Reputation: 63

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)

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 \u2019s and doesn't format it into a new line or \u2019 into " ' " right quotation mark.. so it just shows as this in plaintext

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?

Upvotes: 0

Views: 774

Answers (1)

Samuel Dion-Girardeau
Samuel Dion-Girardeau

Reputation: 3170

I think you might be converting your initial object to a __repr__ instead of a __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.

Upvotes: 1

Related Questions