Neil Dey
Neil Dey

Reputation: 539

Python how to print text with linebreak when it contains '\n'

I have text like n"sdfsdfdsf \n sdfdsfsdf \n sdfdsfdsf..."n. I need to print this text but every time there is a \n, I need to print a linebreak and print the body of text as broken up into separate lines.

how can I do this?

Edit1: I am getting this text from a socket transaction and I just want to print it in a pretty manner.

b'\r\n\r\nSERIAL Debugger\r\n--------------\r\n>fyi * -\r\nThis is a test: 0 (-)\r\nthis is a test\r\nnew level(-)\r\

Upvotes: 0

Views: 788

Answers (1)

warvariuc
warvariuc

Reputation: 59584

You have binary data, and Python doesn't know how you want to print it. So decode it, knowing the encoding the data is in (I used UTF-8):

Python 3.6.1 (default, Mar 23 2017, 16:49:06)

>>> text = b'\r\n\r\nSERIAL Debugger\r\n--------------\r\n>fyi * -\r\nThis is a test: 0 (-)\r\nthis is a test\r\nnew level(-)\r\n'

>>> print(text)
b'\r\n\r\nSERIAL Debugger\r\n--------------\r\n>fyi * -\r\nThis is a test: 0 (-)\r\nthis is a test\r\nnew level(-)\r\n'

>>> print(text.decode())


SERIAL Debugger
--------------
>fyi * -
This is a test: 0 (-)
this is a test
new level(-)

But converting the data for the sake of printing sounds wrong.

Upvotes: 4

Related Questions