Topic 30 of 64
Multi-line String
Overview
Triple-quoted strings (""" or ''') let you write strings spanning multiple lines without escape characters. They are used for docstrings, SQL queries, HTML templates, and long text blocks — essential for readable code.
Syntax
python
# Triple-quoted string
message = """
Hello,
This is a multi-line
string block.
"""
# Docstring (triple-quoted at start of function/class)
def greet(name: str) -> str:
"""Return a greeting for the given name."""
return f"Hello, {name}!"
# Strip leading newline
sql = """SELECT *
FROM users
WHERE active = 1
"""Common Pitfalls
- Triple-quoted strings include all whitespace including leading newlines — use .strip() or a backslash after the opening quotes.
- Docstrings are accessible at runtime via func.__doc__ — they power help() and documentation generators.
- Interview tip: PEP 257 says docstrings should be written in imperative mood: 'Return the sum' not 'Returns the sum'.
Real-World Example
Building a dynamic SQL query using a triple-quoted string
example
python
def build_query(table: str, column: str, value: str) -> str:
return f"""
SELECT *
FROM {table}
WHERE {column} = '{value}'
LIMIT 100;
""".strip()
print(build_query("users", "email", "alice@example.com"))