Python Escape Character Sequences (Examples)

Created with Sketch.

Escape characters in Python are used to represent characters that are difficult to type directly, such as special characters, control characters, or characters with specific meanings. These escape characters are represented by a backslash (\) followed by a character or sequence of characters. Here are some common escape character sequences in Python:

1. Newline (\n):

Used to insert a newline character.

text = "Hello\nWorld"
print(text)

Output:

Hello
World

2. Tab (\t):

Used to insert a tab character.

indented_text = "This is an indented line\twith a tab."
print(indented_text)

Output:

This is an indented line    with a tab.

3. Backslash (\\):

Used to insert a literal backslash.

path = "C:\\Users\\Username\\Documents"
print(path)

Output:

 
C:\Users\Username\Documents

4. Single Quote (\') and Double Quote (\"):

Used to insert a single quote or double quote within a string.

single_quote = 'This is a single quote: \'inside quotes\'.'
double_quote = "This is a double quote: \"inside quotes\"."
print(single_quote)
print(double_quote)

Output:

 
This is a single quote: 'inside quotes'.
This is a double quote: "inside quotes".

5. Backspace (\b):

Used to insert a backspace character.

backspace_text = "Backspace\bCharacter"
print(backspace_text)

Output:

BackspaceCharacter

6. Carriage Return (\r):

Used to move the cursor to the beginning of the line.

text = "Carriage\rReturn"
print(text)

Output:

Returnriage

These are just a few examples of escape character sequences in Python. They are essential for handling special characters and formatting within strings. Understanding and using escape characters can enhance your ability to work with text and manipulate strings effectively in Python.

Leave a Reply

Your email address will not be published. Required fields are marked *