How To Print Special Characters In A String In Python

In Python, special characters are characters that have a predefined meaning in the language, such as newline (\n), tab (\t), or the backslash itself (\\). Sometimes, when working with strings, we need to include these special characters in our output. This tutorial will guide you on how to print special characters in a string in Python.

Step 1: Use escape sequences

Python provides escape sequences to represent special characters in a string. These escape sequences start with a backslash ‘\’ followed by a character that has a special meaning.

Here’s a list of common escape sequences:

\\   - Backslash (\)
\'   - Single quote (')
\"   - Double quote (")
\n   - Newline
\t   - Tab

To include a special character in a string, simply use the corresponding escape sequence.

For example, let’s print a string containing a newline and a tab:



Step 2: Use triple quotes for multi-line strings

Another way to handle special characters, specifically newlines, is to use triple quotes (“”” or ”’). Triple quotes allow you to create multi-line strings without needing to use escape sequences for newlines.

Here’s an example:



Note that triple quotes also allow you to include single or double quotes without needing to escape them.

Step 3: Use raw strings

If you have a string with many backslashes and you don’t want them to be treated as escape characters, you can use a raw string. To create a raw string, simply prefix the string with ‘r’ or ‘R’.

For example, let’s print a string containing two backslashes:



In raw strings, escape sequences are not processed, so the output contains the backslashes as they are.

Full code:


In this tutorial, we’ve covered how to print special characters in a string in Python. By using escape sequences, triple quotes, and raw strings, you can include any special character in your output. Now you should be able to easily add special characters to your Python strings when necessary.