Skip to content Skip to sidebar Skip to footer

Unescaping Escaped Characters In A String Using Python 3.2

Say I have a string in Python 3.2 like this: '\n' When I print() it to the console, it shows as a new line, obviously. What I want is to be able to print it literally as a backsl

Solution 1:

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

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

If you have a string that contains a newline symbol (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

Solution 2:

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

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

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

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

You could use that 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()

Post a Comment for "Unescaping Escaped Characters In A String Using Python 3.2"