How do you add an escape character to a string in python?


Escape Characters

To insert characters that are illegal in a string, use an escape character.

An escape character is a backslash \ followed by the character you want to insert.

An example of an illegal character is a double quote inside a string that is surrounded by double quotes:

Example

You will get an error if you use double quotes inside a string that is surrounded by double quotes:

txt = "We are the so-called "Vikings" from the north."

Try it Yourself »

To fix this problem, use the escape character \":

Example

The escape character allows you to use double quotes when you normally would not be allowed:

txt = "We are the so-called \"Vikings\" from the north."

Try it Yourself »

Other escape characters used in Python:

CodeResultTry it
\' Single Quote Try it »
\\ Backslash Try it »
\n New Line Try it »
\r Carriage Return Try it »
\t Tab Try it »
\b Backspace Try it »
\f Form Feed
\ooo Octal value Try it »
\xhh Hex value Try it »



I'm trying to escape the characters -]\^$*. each with a single backslash \.

For example the string: ^stack.*/overflo\w$arr=1 will become:

\^stack\.\*/overflo\\w\$arr=1

What's the most efficient way to do that in Python?

re.escape double escapes which isn't what I want:

'\\^stack\\.\\*\\/overflow\\$arr\\=1'

I need this to escape for something else (nginx).

asked Sep 21, 2013 at 17:55

1

This is one way to do it (in Python 3.x):

escaped = a_string.translate(str.maketrans({"-":  r"\-",
                                          "]":  r"\]",
                                          "\\": r"\\",
                                          "^":  r"\^",
                                          "$":  r"\$",
                                          "*":  r"\*",
                                          ".":  r"\."}))

For reference, for escaping strings to use in regex:

import re
escaped = re.escape(a_string)

answered Sep 21, 2013 at 17:56

rlmsrlms

10.3k8 gold badges43 silver badges58 bronze badges

4

Just assuming this is for a regular expression, use re.escape.

answered Sep 21, 2013 at 17:57

How do you add an escape character to a string in python?

Ry-Ry-

212k54 gold badges442 silver badges456 bronze badges

2

re.escape doesn't double escape. It just looks like it does if you run in the repl. The second layer of escaping is caused by outputting to the screen.

When using the repl, try using print to see what is really in the string.

$ python
>>> import re
>>> re.escape("\^stack\.\*/overflo\\w\$arr=1")
'\\\\\\^stack\\\\\\.\\\\\\*\\/overflo\\\\w\\\\\\$arr\\=1'
>>> print re.escape("\^stack\.\*/overflo\\w\$arr=1")
\\\^stack\\\.\\\*\/overflo\\w\\\$arr\=1
>>>

answered May 5, 2016 at 11:14

rjmunrorjmunro

26.4k20 gold badges108 silver badges132 bronze badges

Simply using re.sub might also work instead of str.maketrans. And this would also work in python 2.x

>>> print(re.sub(r'(\-|\]|\^|\$|\*|\.|\\)',lambda m:{'-':'\-',']':'\]','\\':'\\\\','^':'\^','$':'\$','*':'\*','.':'\.'}[m.group()],"^stack.*/overflo\w$arr=1"))
\^stack\.\*/overflo\\w\$arr=1

answered Jan 8, 2016 at 7:04

Akshay HazariAkshay Hazari

3,0393 gold badges43 silver badges76 bronze badges

Utilize the output of built-in repr to deal with \r\n\t and process the output of re.escape is what you want:

re.escape(repr(a)[1:-1]).replace('\\\\', '\\')

answered Mar 26, 2016 at 11:48

How do I add an escape character to a string?

To insert characters that are illegal in a string, use an escape character. An escape character is a backslash \ followed by the character you want to insert.

What is the escape character for in Python?

1. Escape sequence in python using strings. In Python strings, the backslash “ ” is a special character, also called the “escape” character. It is used in representing certain whitespace characters: “\t” is a tab, “\n” is a new line, and “\r” is a carriage return.

How do you show escape characters in Python?

Python has special “escape characters” that start with the single backslash such as \n , \t , and \" . If you print a string with escape characters, Python prints the special meaning—for example, a new line for the newline character \n . What is this? s = "Learn\tprogramming\nwith\t\tFinxter!"

What is the way to include backslash characters in a string?

If you want to include a backslash character itself, you need two backslashes or use the @ verbatim string: var s = "\\Tasks"; // or var s = @"\Tasks"; Read the MSDN documentation/C# Specification which discusses the characters that are escaped using the backslash character and the use of the verbatim string literal.