Sitemap

Python — String(Part 5)

2 min readMar 5, 2025

--

Escape Characters

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

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

Get Sithila Sihan Somaratne’s stories in your inbox

Join Medium for free to get updates from this writer.

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

text = "There's a community called \"Little Italy\" in Lower Manhattan."
'''
OUTPUT:

You will get an error if you use double quotes inside a string
that is surrounded by double quotes. In fact you get a SyntaxError.

'''

To fix this problem, use the escape character \" on both sides. It allows you to use double quotes when you normally would not be allowed:

text = "There's a community called \"Little Italy\" in Lower Manhattan."
print(text) # There's a community called "Little Italy" in Lower Manhattan.

Other Escape Characters

There are other escape characters used in Python as shown in this table:

Press enter or click to view image in full size
Table from AirTable for other escape characters table
Table from AirTable for other escape characters table

Both outputs for \n and \r escape characters are the same but they are different. The newline character is represented by \n & it is used to create a new line in the string or file. The carriage return character represented by \r moves the cursor to the beginning of the current line without advancing to the next line.

The \f escape character or the form feed character is used to move the cursor to the next page, which the program represents by additional leading spaces on the second line.

--

--

Sithila Sihan Somaratne
Sithila Sihan Somaratne

Written by Sithila Sihan Somaratne

I'm a student. I love programming and I would like to become a Senior Software Engineer.