如何在Python中修剪此文本?

2024-10-02 22:25:09 发布

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

我的脚本以一种奇怪的方式返回文本,我需要对其进行修剪以使其可读。你知道吗

这是返回文本的示例:

b'\r\nR5#'b'e'b'n'b'\r\n'b'R5#'b'c'b'o'b'n'b'f'b' t'b'\r\n'b'Enter configuration commands, one per line. End with CNTL/Z.\r\nR5(config)#'b'h'b'o'b's'b't'b'n'b'a'b'm'b'e'b' 'b'R'b'5'b'\r\n'b'R5(config)#'

这是文本的显示方式,有换行符,没有“b”\r\n:

R5#en
R5#conf t
Enter configuration commands, one per line. End with CNTL/Z.
R5(config)#hostname R5
R5(config)#

如何在Python中正确地修剪/拆分它?你知道吗


Tags: 文本脚本configwith方式lineoneconfiguration
2条回答

你得到的是字节。您可以通过将其解码为字符串来获得所需的输出。你知道吗

s = b'\r\nR5#'b'e'b'n'b'\r\n'b'R5#'b'c'b'o'b'n'b'f'b' t'b'\r\n'b'Enter configuration commands, one per line. End with CNTL/Z.\r\nR5(config)#'b'h'b'o'b's'b't'b'n'b'a'b'm'b'e'b' 'b'R'b'5'b'\r\n'b'R5(config)#'

print(s.decode('utf-8'))

您可以从这个相关问题中找到更多信息: Convert bytes to a string?

Python3

s=b'\r\nR5#'b'e'b'n'b'\r\n'b'R5#'b'c'b'o'b'n'b'f'b' t'b'\r\n'b'Enter configuration commands, one per line. End with CNTL/Z.\r\nR5(config)#'b'h'b'o'b's'b't'b'n'b'a'b'm'b'e'b' 'b'R'b'5'b'\r\n'b'R5(config)#'
s=s.strip().decode("utf-8")
print(s)

enter image description here

相关问题 更多 >