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:
1 |
print("Hello,\n\tWorld!") |
Output:
Hello, World!
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:
1 2 3 4 |
multiline_string = """Hello, World!""" print(multiline_string) |
Output:
Hello, World!
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:
1 |
print(r"Hello,\\World!") |
Output:
Hello,\\World!
In raw strings, escape sequences are not processed, so the output contains the backslashes as they are.
Full code:
1 2 3 4 5 6 7 |
print("Hello,\n\tWorld!") multiline_string = """Hello, World!""" print(multiline_string) print(r"Hello,\\World!") |
Conclusion
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.