Kodeclik Blog
Python Escape Characters
The term “escape character” sounds like we are doing something surreptitiously but in reality it is a simple idea.
What is an escape character?
Let us suppose we want to print ‘Hello World’ in python. You will do:
print(‘Hello World’)
This will give the output:
Hello World
But what if you also wanted the quotes, before and after your string? How do you tell Python that you mean quotes literally and not just as denoting the beginning and end of a string? This is where escape characters come in!
You should write your program as:
print(‘\’Hello World\’’)
Note that the string inside the print statement still has a beginning quote and end quote. But in between these quotes, there are other quotes prefixed by a backslash. This creates the escape character (\’) which means to print a quote literally. The output will be:
'Hello World'
as desired.
When should you use an escape character?
Escape characters are essential when you need to include special characters in Python strings that would otherwise cause syntax errors or unintended behavior.
Example 1: Including Quotes in Strings
As mentioned earlier, the most common use case for escape characters is when your string contains quotes that match the enclosing quotes. You escape them using \' or \":
txt = "She said, \"Hello!\""
print(txt)
The output will be:
She said, "Hello!"
Example 2: Adding Newlines or Tabs
Use \n for newlines and \t for tabs to format text output. For instance:
print("First Line\nSecond Line")
print("Column1\tColumn2")
The output will be:
First Line
Second Line
Column1 Column2
Example 3: Including Backslashes
To display a backslash (\), you need to escape it with another backslash (\\):
path = "C:\\Users\\Name\\Documents"
print(path)
The output is:
C:\Users\Name\Documents
Example 4: Using Unicode Characters
Escape sequences like \u and \U allow you to include Unicode characters in strings:
print("\u03A9 is Omega")
The output is:
Ω is Omega
What other escape characters are available?
Below is a printing of escape characters in Python that you can use as a reference:
symbols = [
'\u00A9', # ©
'\u00AE', # ®
'\u2190', # ←
'\u2192', # →
'\u21D2', # ⇒
'\u21D4', # ⇔
'\u20AC', # €
'\u2605', # ★
'\u2606', # ☆
'\u2764', # ❤
'\U0001F600', # 😀
'\U0001F4A9', # 💩
'\U0001F680', # 🚀
'\U0001F47D', # 👽
'\u260E', # ☎
'\u262F', # ☯
]
cols = 4
for i in range(0, len(symbols), cols):
row = symbols[i:i+cols]
print(' '.join(f'{char:^5}' for char in row))
The output will be as expected, a grid of 4x4 characters:
© ® ← →
⇒ ⇔ € ★
☆ ❤ 😀 💩
🚀 👽 ☎ ☯
Conclusion
By mastering escape characters, you can handle complex string formatting tasks with ease and precision.
Enjoy this blogpost? Want to learn Python with us? Sign up for 1:1 or small group classes.