Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 backslash followed by an n. Further, I need to do this for all escaped characters, such as \t. So I'm looking for a function unescape() that, for the general case, would work as follows:

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

Is this possible in Python without constructing a dictionary of escaped characters to their literal replacements?

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

like image 861
Mike Chamberlain Avatar asked Feb 18 '12 07:02

Mike Chamberlain


People also ask

How do you escape characters in a string in Python?

Escape sequences allow you to include special characters in strings. To do this, simply add a backslash ( \ ) before the character you want to escape.

What is the '\ n escape character?

Escape sequences are used inside strings, not just those for printf, to represent special characters. In particular, the \n escape sequence represents the newline character.

What are all the escape characters in Python?

These characters are referred to as special characters. Some examples are double quotes ("), single quotes ('), etc. To print these special characters, a backslash (\) is used. This black slash is called an escape sequence .

How do I add a forward slash to a string in Python?

How do you escape a forward slash in Python string? The python backslash character ( \ ) is a special character used as a part of a special sequence such as \t and \n . Use the Python backslash ( \ ) to escape other special characters in a string.


1 Answers

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
like image 120
jfs Avatar answered Sep 22 '22 02:09

jfs