Strings II

Escape Characters

Learn how to use escape characters in Python to insert special characters like newlines, tabs, and quotes into strings.


Let's talk about special characters in Python strings.

Imagine you want to represent the sentence She said, "It's a beautiful day!" in a Python string.

If you try that, you'll notice that Python interprets the second single quote as the end of your string and doesn't know what to do with the rest of your sentence.

'She said, "It's a beautiful day!"'
Python

In this case, we'll need to use of an escape character.

Escape characters in Python allow you to insert special characters into strings that would otherwise be difficult or impossible to type or display directly.

An escape character is represented by a backslash \ followed by another character.

The escape character we'll need in our example is \'.

The escape character \' allows us to include a single quote inside a string without breaking it.

Let's try it:

print('She said, "It\'s a beautiful day!"')
Python
Output

Great! Now, we can represent complex dialogues in Python strings.

Instead of single quotes, you can also escape double quotes with \".

This is useful if you prefer to enclose your strings with double quotes. For example:

print("She said, \"It's a beautiful day!\"")
Python
Output

Another commonly used escape character is the newline character \n.

As the name suggests, it inserts a new line within the string. For example:

print("Hi, how are you?\nI'm great!")
Python
Output

But, what if you want to display a literal backslash \ in your string?

Since the backslash is reserved for escape characters in Python, you need to escape it by using a double backslash \\:

print("Here's a backslash: \\")
Python
Output

Great! Let's see if you understood.


What will be the output?

print("She said, \"Hello!\"")
Python

What will be the output?

print('Hi there. How's it going?')
Python

What will be the output?

print('Line 1\nLine 2')
Python

What will be the output?

print('Line 1\\nLine 2')
Python

While we've covered some common escape characters, there are many more.

If you need to display a special character in a Python string and are unsure how, there's likely an escape character for it.

A quick internet search will help you out in most cases.