In Python, working with strings sometimes involves multi-line text, quotes inside text, or file paths with many backslashes. Writing such strings can quickly become confusing or error-prone.
To handle these cases efficiently, Python provides two features: triple quotes, which allow multi-line text or text containing both single and double quotes without escaping, and raw strings, which treat backslashes literally so escape sequences like \n or \t are not processed.
Understanding these features makes string handling cleaner and easier to manage in your programs. Let’s start by exploring how triple quotes simplify strings that contain quotes or span multiple lines.
Visit Python Strings vs Numbers.
Triple Quotes as an Alternative
When working with multi-line strings or text that contains both single and double quotes, using triple quotes (”’ or “””) is often a cleaner and more readable option than using escape sequences.
They allow you to include quotes freely within a string without worrying about escaping them. Triple-quoted strings are also perfect for writing paragraphs, docstrings, or formatted text blocks that span multiple lines.
Example: Triple Quotes
paragraph = """She said, "Python is amazing!" and left the room."""
print(paragraph)
#Output:
She said, "Python is amazing!" and left the room.
Explanation:
Triple quotes (“”” or ”’) eliminate the need to escape internal quotes. This makes your code more readable — especially when embedding both single and double quotes, long text, or documentation.
Raw Strings: Disabling Escape Characters
In Python, prefixing a string with r (or R) creates a raw string literal.
This tells Python to treat backslashes (\) as ordinary characters instead of escape sequences.
Raw strings are especially useful when working with file paths, regular expressions, or Windows directories, where backslashes are common.
Example: Raw Strings
path = r"C:\Users\Rahul\Documents\Projects"
print(path)
#Output:
C:\Users\Rahul\Documents\Projects
Explanation: By using the r prefix, Python doesn’t interpret \U, \n, or \t as special characters. This is why raw strings are often the go-to choice when defining file paths or regex patterns.
Quick Comparison: Triple Quotes vs Raw Strings
| Feature | Triple Quotes (”’ or “””) | Raw Strings (r”…”) |
|---|---|---|
| Purpose | Used for multi-line or quoted strings | Used to disable escape character interpretation |
| Ideal For | Multi-line text, docstrings, embedded quotes | File paths, regex, and strings with many backslashes |
| Supports Escape Sequences | Yes | No |
| Example | “””He said, “Hello!”””” | r”C:\folder\path” |