如何在Python中修剪此文本?

时间:2019-04-30 10:22:20

标签: 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中正确修剪/拆分?

2 个答案:

答案 0 :(得分:1)

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

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?

答案 1 :(得分:0)

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