Last Updated : 11 Mar, 2025
In Python, escape characters like \n (newline) and \t (tab) are used for formatting, with \n moving text to a new line and \t adding a tab space. By default, Python interprets these sequences, so I\nLove\tPython will display "Love" on a new line and a tab before "Python." However, if you want to display the escape characters themselves as raw text (e.g., I\nLove\tPython), you can use different methods.
Using repr()repr() function efficiently preserves escape characters in their raw form, making it the best way to display them without interpretation. It returns the official string representation, ensuring escape sequences remain visible.
Python
s = "I\nLove\tPython"
print(repr(s))
Explanation: repr()
ensures escape characters remain visible rather than being interpreted.
A raw string prevents Python from interpreting escape sequences, making it useful when working with file paths and regular expressions.
Python
s = r"I\nLove\tPython"
print(s)
Explanation: The r prefix ensures \n and \t are displayed as-is, making raw strings useful for file paths and regex.
Using double backslashes(\\)By manually doubling backslashes, escape sequences are prevented from being interpreted. This approach is straightforward but requires additional effort when writing strings.
Python
s = "I\\nLove\\tPython"
print(s)
Explanation: The \\ ensures \n and \t are treated as literal text instead of formatting commands.
Using encode() and decode()Encoding a string with unicode_escape and decoding it back ensures escape characters remain intact. This method is useful for data processing but adds computational overhead.
Python
s = "I\nLove\tPython"
print(s.encode("unicode_escape").decode("utf-8"))
Explanation: Converts escape characters into their escaped forms (\\n and \\t), making them visible.
Using json.dumps()json.dumps() function preserves escape sequences in JSON format, making it useful for data serialization. However, it is less efficient due to additional processing.
Python
import json
s = "I\nLove\tPython"
print(json.dumps(s))
Explanation: Converts the string into a JSON-compliant format, retaining escape sequences.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4