Question
How to Split Long Strings Across Multiple Lines in Python
Question
I have a very long SQL query and want to split it across multiple lines in Python for better readability.
In JavaScript, I might write something like this:
var longString = 'some text not important. just garbage to' +
'illustrate my example';
I tried something similar in Python, but it did not work the way I expected. Instead, I used backslashes (\) for line continuation:
query = 'SELECT action.descr as "action", '\
'role.id as role_id,'\
'role.descr as role'\
'FROM '\
'public.role_action_def,'\
'public.role,'\
'public.record_def, '\
'public.action'\
'WHERE role.id = role_action_def.role_id AND'\
'record_def.id = role_action_def.def_id AND'\
'action.id = role_action_def.action_id AND'\
'role_action_def.account_id = ' + account_id + ' AND'\
'record_def.account_id=' + account_id + ' AND'\
'def_id=' + def_id
Is this the only or best Pythonic way to split a long string literal over multiple lines? Is there a cleaner approach for long strings such as SQL queries?
Short Answer
By the end of this page, you will understand how Python handles long string literals across multiple lines, why backslashes are usually not the best choice, and which approaches are considered more readable and Pythonic. You will also see safer ways to build SQL queries and avoid common string-formatting mistakes.
Concept
In Python, long strings can be split across multiple lines in several ways, but the most Pythonic approach depends on what you want:
- If you want one string value written across multiple source-code lines, Python allows implicit string literal concatenation inside parentheses.
- If you want actual newline characters inside the string, you can use triple-quoted strings.
- If you need to insert variables into the string, you can use f-strings,
.format(), or parameterized queries depending on the context.
A key Python feature is that adjacent string literals are automatically joined at compile time:
text = (
"Hello, "
"world"
)
This becomes:
"Hello, world"
No + is required.
This matters because readable code is easier to maintain. Long SQL queries, error messages, file paths, and templates often become hard to read on one line. Python gives you cleaner options than using many backslashes.
For SQL specifically, there is another important issue: building queries by concatenating values into strings can be unsafe and can lead to SQL injection bugs. Even if your current question is about line splitting, in real code you should usually use parameterized queries instead of manually combining values into the SQL string.
Mental Model
Think of Python string literals like puzzle pieces.
- If you place string literal pieces next to each other inside parentheses, Python snaps them together into one string.
- If you use
+, you are explicitly asking Python to join strings. - If you use triple quotes, you are writing the text more like a block note, including line breaks.
So:
- Adjacent literals in parentheses = puzzle pieces combined automatically
+operator = manually glueing pieces together- Triple quotes = writing the whole note exactly as it appears
For readable code, Python usually prefers the first or third option over backslashes.
Syntax and Examples
1. Implicit concatenation with parentheses
This is the most common Pythonic way to split a long string literal across lines.
query = (
"SELECT action.descr AS action, "
"role.id AS role_id, "
"role.descr AS role "
"FROM public.role_action_def, public.role, public.record_def, public.action "
"WHERE role.id = role_action_def.role_id"
)
Python joins all adjacent string literals into one string.
2. Triple-quoted strings
Use this when you want the string to contain line breaks exactly as written.
query = """
SELECT action.descr AS action,
role.id AS role_id,
role.descr AS role
FROM public.role_action_def,
public.role,
public.record_def,
public.action
WHERE role.id = role_action_def.role_id
"""
This is often great for SQL because the query stays formatted like SQL.
3. Mixing variables with f-strings
If you need to insert variables, f-strings are cleaner than repeated +.
account_id = 10
def_id = 5
query = (
f"SELECT * FROM public.role_action_def "
f"WHERE account_id = {account_id} "
f"AND def_id = {def_id}"
)
This is more readable than:
Step by Step Execution
Consider this example:
query = (
"SELECT * "
"FROM users "
"WHERE active = 1"
)
print(query)
What happens step by step
- Python sees the opening parenthesis after
=. - Inside the parentheses, it finds several string literals placed next to each other.
- Because they are adjacent string literals, Python automatically concatenates them.
- The final value stored in
queryis:
"SELECT * FROM users WHERE active = 1"
print(query)outputs:
SELECT * FROM users WHERE active = 1
Important detail
This does not add newline characters between the lines in your source code. It just joins the text.
If you want actual newlines, write them explicitly:
query = (
"SELECT *\n"
"FROM users\n"
"WHERE active = 1"
)
Or use triple quotes:
Real World Use Cases
Long strings appear often in real programs. Common examples include:
- SQL queries
- Multi-line
SELECT,INSERT, orUPDATEstatements
- Multi-line
- Error messages
- User-friendly messages that are too long for one line
- HTML or email templates
- Small chunks of markup or message bodies
- API URLs
- Long endpoints with query parameters
- Log messages
- Structured strings with multiple parts
- Command-line commands
- Shell commands assembled for scripts or automation
Example: readable API URL construction
url = (
"https://api.example.com/search?"
"category=books&"
"sort=price"
)
Example: readable user message
message = (
"Your account was created successfully. "
"Please check your email to verify your address."
)
Real Codebase Usage
In real Python codebases, developers often use these patterns:
Guard readability with parentheses
Parentheses are preferred over backslashes because they are less fragile and easier to format.
message = (
"This operation failed because the provided token expired "
"before the request was completed."
)
Keep SQL formatted like SQL
Triple-quoted strings are common for database queries because they preserve indentation and line breaks.
query = """
SELECT id, email
FROM users
WHERE active = %s
"""
Use parameterized queries for validation and safety
Developers do not usually build SQL by concatenating user values directly.
query = "SELECT id FROM users WHERE email = %s"
params = (email,)
Use early formatting only for trusted display text
For messages, logs, and filenames, f-strings are common.
filename = f"report_{year}_{month}.csv"
Break large templates into clear sections
When strings contain multiple logical parts, developers often group them neatly.
help_text = (
)
Common Mistakes
1. Using backslashes unnecessarily
Backslashes work, but they are easy to misuse and are usually less readable.
query = 'SELECT * FROM users '\
'WHERE active = 1'
Prefer:
query = (
"SELECT * FROM users "
"WHERE active = 1"
)
2. Forgetting spaces between string parts
Python joins the strings exactly as written.
query = (
"SELECT * "
"FROM users"
"WHERE active = 1"
)
print(query)
Output:
SELECT * FROM usersWHERE active = 1
Fix it by including spaces where needed:
query = (
"SELECT * "
"FROM users "
"WHERE active = 1"
)
3. Confusing source-code line breaks with string line breaks
This code does not create newlines in the string:
text = (
"line one"
)
Comparisons
| Approach | Best for | Adds newline characters? | Readability | Notes |
|---|---|---|---|---|
| Adjacent string literals in parentheses | Long string literals split across code lines | No | High | Most Pythonic for simple splitting |
+ operator | Joining dynamic string parts | No | Medium | Fine, but often noisier |
Backslash \ line continuation | Rare cases | No | Low | Usually avoid when parentheses work |
| Triple-quoted strings | Multi-line text blocks | Yes | High | Great for SQL, emails, templates |
Cheat Sheet
Quick reference
Split a long string without newlines
text = (
"part one "
"part two "
"part three"
)
Create a multi-line string with real line breaks
text = """
part one
part two
part three
"""
Insert variables
name = "Sam"
text = f"Hello, {name}"
Safer SQL pattern
query = "SELECT * FROM users WHERE id = %s"
params = (user_id,)
Rules to remember
- Adjacent string literals are automatically concatenated.
- Parentheses let you split code across lines cleanly.
- Backslashes are usually unnecessary for long strings.
- Triple quotes preserve line breaks.
- Use f-strings for readable variable insertion.
- Use parameterized queries for SQL values.
- Remember to include spaces manually between joined string parts.
Common edge cases
# No automatic space added
text = (
"hello"
"world"
)
FAQ
Can I split a Python string across lines without using +?
Yes. Put adjacent string literals inside parentheses. Python joins them automatically.
Is using backslash for long strings bad in Python?
It is not wrong, but it is usually less readable and less preferred than using parentheses.
Do triple-quoted strings add real line breaks?
Yes. Triple-quoted strings preserve newline characters as part of the string.
What is the most Pythonic way to split a long SQL query?
Usually a triple-quoted string for readability, combined with parameterized query values.
Why does my joined string miss spaces?
Because Python joins the text exactly as written. You must include spaces at the end or beginning of each part where needed.
Should I use + to build SQL queries in Python?
Usually no. Use parameterized queries instead to avoid SQL injection and formatting bugs.
Are adjacent string literals efficient?
Yes. Python handles literal concatenation efficiently, and for normal code readability this is completely fine.
When should I use f-strings instead?
Use f-strings when the string contains variables and you want a readable way to insert their values.
Mini Project
Description
Build a small Python example that creates readable SQL query strings in two ways: one with implicit string literal concatenation and one with a parameterized multi-line query. This demonstrates how to keep long strings readable while also using a safer real-world SQL pattern.
Goal
Create clean, readable long SQL strings in Python and pass values separately instead of concatenating them into the query.
Requirements
- Create one query using parentheses and adjacent string literals.
- Create one query using a triple-quoted multi-line string.
- Include dynamic values such as
account_idanddef_id. - Show the safer parameterized version for the dynamic query.
- Print the query text and parameters.
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Call a Function by Name in a Python Module
Learn how to call a function by name in a Python module using strings, getattr, and safe patterns for dynamic function dispatch.
Catch Multiple Exceptions in One except Block in Python
Learn how to catch multiple exceptions in one Python except block using tuples, with examples, mistakes, and real-world usage.