How to trim this text in Python?

Asked by At

My script returns text in a weird way, and i need to trim it so it becomes readable.

This is an example of the return text:

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)#'

This is how the text should appear, with line breaks and without the 'b'\r\n:

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

How can i trim/split this correctly in Python?

2 Answers

1
Community On

What you're getting is bytes. You can get the desired output by decoding it into a string.

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'))

You can find more information from this related question: Convert bytes to a string?

0
Karthick Aravindan On

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