When working with text data in Python, you'll often encounter situations where you need to use multi-line strings or include special characters like newlines, tabs, or quotes. Python provides elegant solutions for both through multi-line strings and escape sequences.
This tutorial explains how to create and use multi-line strings, and how to work with escape sequences to make your strings more powerful and readable.
1. What Are Multi-line Strings?
Multi-line strings are strings that span multiple lines. They are created using triple quotes — either '''
(single quotes) or """
(double quotes).
Example 1: Multi-line string with triple quotes
text = '''This is a multi-line string.
It can span across several lines.
Useful for writing long paragraphs.'''
print(text)
Output:
This is a multi-line string. It can span across several lines. Useful for writing long paragraphs.
Example 2: Triple double quotes
message = """Dear User,
Your order has been confirmed.
Thanks,
Team"""
print(message)
2. Using Multi-line Strings as Docstrings
Triple-quoted strings are also commonly used as docstrings to document functions, classes, and modules.
def greet(name):
"""This function greets the user by name."""
return f"Hello, {name}!"
You can access the docstring using:
print(greet.__doc__)
3. What Are Escape Sequences?
Escape sequences are special characters preceded by a backslash \
. They allow you to insert characters that are difficult to type directly into a string.
Common escape sequences:
Escape Sequence | Meaning | Example |
---|---|---|
\n |
Newline | "Hello\nWorld" |
\t |
Tab | "Name:\tJohn" |
\\ |
Backslash | "Folder\\Subfolder" |
\' |
Single quote | 'It\'s easy' |
\" |
Double quote | "She said, \"Hi\"" |
4. Examples of Escape Sequences
Example 1: Newlines
print("Line 1\nLine 2\nLine 3")
Example 2: Tabs
print("Name:\tJohn\tAge:\t30")
Example 3: Quotes inside strings
print('It\'s a beautiful day!')
print("She said, \"Hello there!\"")
Example 4: Backslashes
path = "C:\\Users\\John\\Documents"
print(path)
5. Raw Strings
If you want to avoid processing escape sequences, use a raw string by prefixing it with r
. This is useful for regular expressions and file paths.
raw_path = r"C:\Users\John\Documents"
print(raw_path) # Output: C:\Users\John\Documents
6. Summary
- Use triple quotes (
'''
or"""
) for multi-line strings and documentation. - Escape sequences allow special characters like newline (
\n
), tab (\t
), and quotes. - Use raw strings (
r""
) to ignore escape sequences in file paths or regular expressions.
7. Final Thoughts
Multi-line strings and escape sequences enhance the flexibility of working with text in Python. Whether you're writing long messages, dealing with file paths, or formatting output, mastering these features will help you write cleaner and more readable code.