Unescaping escape characters in a string using Python 3.2

Let's say I have a line in Python 3.2, like this:

'\n' 

When I type () it on the console, it shows as a new line, obviously. I want to be able to print it literally as a backslash followed by n. In addition, I need to do this for all escaped characters, such as \ t. Therefore, I am looking for the unescape () function, which for the general case will work as follows:

 >>> s = '\n\t' >>> print(unescape(s)) '\\n\\t' 

Is this possible in Python without creating a dictionary of escaped characters for literal replacements?

(In case anyone is interested, the reason I do this is because I need to pass the string to an external program on the command line. This program understands all standard escape sequences.)

+6
source share
2 answers

To prevent special handling \ in string literature, you can use the r prefix:

 s = r'\n' print(s) # -> \n 

If you have a string containing a newline character ( ord(s) == 10 ), and you would like to convert it to a form suitable as a Python literal:

 s = '\n' s = s.encode('unicode-escape').decode() print(s) # -> \n 
+11
source

Change Based on your last comment, you will most likely want to switch from Unicode to some encoded representation. This is one way:

 >>> s = '\n\t' >>> s.encode('unicode-escape') b'\\n\\t' 

If you do not need screens, use system encoding, for example:

 >>> s.encode('utf8') b'\n\t' 

You can use this in a subprocess:

 import subprocess proc = subprocess.Popen([ 'myutility', '-i', s.encode('utf8') ], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT) stdout,stderr = proc.communicate() 
+5
source

Source: https://habr.com/ru/post/908764/


All Articles