Python 当包含 '\n' 时如何打印带有换行符的文本
Python how to print text with linebreak when it contains '\n'
我有 n"sdfsdfdsf \n sdfdsfsdf \n sdfdsfdsf..."
n 这样的文字。我需要打印这段文字,但每次出现 \n
时,我都需要打印一个换行符并将正文打印成单独的行。
我该怎么做?
编辑1:
我从套接字事务中获取此文本,我只想以漂亮的方式打印它。
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\
您有二进制数据,Python不知道您要如何打印它。所以解码它,知道数据的编码(我使用 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(-)
但是为了打印而转换数据听起来是错误的。
我有 n"sdfsdfdsf \n sdfdsfsdf \n sdfdsfdsf..."
n 这样的文字。我需要打印这段文字,但每次出现 \n
时,我都需要打印一个换行符并将正文打印成单独的行。
我该怎么做?
编辑1: 我从套接字事务中获取此文本,我只想以漂亮的方式打印它。
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\
您有二进制数据,Python不知道您要如何打印它。所以解码它,知道数据的编码(我使用 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(-)
但是为了打印而转换数据听起来是错误的。