Replacing a text with \n in it, with a real \n output

五迷三道 提交于 2019-12-10 17:15:32

问题


I am trying to get a config from a juniper router and I have the following problem:

After setting this

stdin, stdout, stderr = client1.exec_command('show configuration interfaces %s' % SID)
 CONFIG = stdout.read()
 print CONFIG

It brings me something like these

'description El_otro_Puerto_de_la_Routing-instance;\nvlan-id 309;\nfamily inet {\n    mtu 1600;\n    address 10.100.10.10/24;\n}\n'

and the problem is that I want to receive that information in this format:

'description El_otro_Puerto_de_la_Routing-instance;
 nvlan-id 309;
 nfamily inet {
  mtu 1600;
  address 10.100.10.10/24;
 }

So I want the \n to actually be a new line, and not just to show me the "\n" string.


回答1:


If you're running this in the Python interpreter, it is the regular behavior of the interpreter to show newlines as "\n" instead of actual newlines, because it makes it easier to debug the output. If you want to get actual newlines within the interpreter, you should print the string you get.

If this is what the program is outputting (i.e.: You're getting newline escape sequences from the external program), you should use the following:

OUTPUT = stdout.read()
formatted_output = OUTPUT.replace('\\n', '\n')
print formatted_output

This will replace escaped newlines by actual newlines in the output string.




回答2:


An alternative to what you want is splitting your string into a list of strings (per line).

mystr = 'a\nb\nc'
mystr = mystr.split(sep='\n')
print(mystr)
#this will be your print output:['a', 'b', 'c']
for s in mystr:
    print(s)
#your print output:
#a
#b
#c



回答3:


This also works:

CONFIG = """{}""".format(CONFIG)


来源:https://stackoverflow.com/questions/42965689/replacing-a-text-with-n-in-it-with-a-real-n-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!