w3resource

How do escape characters work in Python strings? Provide some examples

Escape characters in Python. Provide some examples

Escape characters in Python strings include special characters that cannot be directly represented in the string itself. They are indicated by a backslash (/) followed by a specific character, and they alter the interpretation of the subsequent character or sequence.

Here are some examples of escape characters in Python strings:

Example: Newline (\n)

It represents a line break, and it is used to start the first line in the string.

Code:

multiline_string = "Python interview\nQuestions and answers."
print(multiline_string)

Output:

Python interview
Questions and answers.

Example: Tab (\t)

This represents a horizontal tab for creating horizontal indentation.

Code:

indented_text = "Red\tGreen\tBlue\tOrange" 
print(indented_text)

Output:

Red	Green	Blue	Orange

Example: Backslash (\\)

Backslashes must be escaped with another backslash in a Python string.

Code:

backslash_string = "This is a backslash \\ in the string."
print(backslash_string)

Output:

This is a backslash \ in the string.

Example: Single Quote (\') and Double Quote (\"):

If we want to include single or double quotes in a string enclosed in the same type of quote, you need to escape them with a backslash.

Code:

single_quote_string = 'String with a single quote (\').'
double_quote_string = "String with a double quote (\")."
print(single_quote_string)
print(double_quote_string)

Output:

String with a single quote (').
String with a double quote (").

Example: Unicode Escape (\u and \U)

To include Unicode characters in a string, we can use the \u escape followed by four hexadecimal digits or the \U escape followed by eight hexadecimal digits.

Code:

unicode_str1 = "\u03A9 is the Greek letter Omega."
unicode_str2 = "\u03b3 is the Greek letter Gamma."
print(unicode_str1)
print(unicode_str2)

Output:

Ω is the Greek letter Omega.
γ is the Greek letter Gamma.


Follow us on Facebook and Twitter for latest update.