[ACCEPTED]-Unescaping escaped characters in a string using Python 3.2-python-3.x

Accepted answer
Score: 13

To prevent special treatment of \ in a literal 4 string you could use r prefix:

s = r'\n'
# -> \n

If you have 3 a string that contains a newline symbol 2 (ord(s) == 10) and you would like to convert it to a 1 form suitable as a Python literal:

s = '\n'
s = s.encode('unicode-escape').decode()
# -> \n
Score: 5

Edit: Based on your last remark, you likely 4 want to get from Unicode to some encoded 3 representation. This is one way:

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

If you don't 2 need them to be escaped then use your system 1 encoding, e.g.:

>>> s.encode('utf8')

You could use that in a subprocess:

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

More Related questions