-1

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?

Telmo
  • 127
  • 8
  • 1
    Is it the content of a variable? How did you examine that result - did you try to `print` the said variable? – SpghttCd Apr 30 '19 at 10:28
  • Please show the code that output the text. Is it a `print`, `repr` or `str` call? What is the text? `str` or `bytes` or something else entirely? – Mad Physicist Apr 30 '19 at 10:28
  • 1
    See [**`ast.literal_eval`**](https://docs.python.org/3/library/ast.html). – Peter Wood Apr 30 '19 at 10:29

2 Answers2

1

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?

Jizhou Yang
  • 138
  • 5
  • 1
    I'm not sure that OP has provided enough information to justify the first assertion. – Mad Physicist Apr 30 '19 at 10:34
  • 1
    Hi. Thank you all for your quick help. You are correct, and i'm sorry. I can decode it and it works perfectly in python's shell. But this text will be shown in an html page. And it doesn't break if i simply decode it. So i'd like to trim it and split it correctly, so i can then print each line to html. – Telmo Apr 30 '19 at 12:47
  • The code is posted here: [link]https://stackoverflow.com/questions/55901968/paramiko-split-lines-in-html-page But i'm thinking of an alternative way to solve my problem. – Telmo Apr 30 '19 at 12:53
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

Karthick Aravindan
  • 1,042
  • 3
  • 12
  • 19
  • 1
    Please don't post images if not really necessary. You can paste the return value if your solution in the same way like your code; often it's commented to separate it visually from the code. – SpghttCd Apr 30 '19 at 18:04
  • @SpghttCd sure, I will follow your advice. Thanks – Karthick Aravindan May 02 '19 at 10:51