How to write a multiline string in Python

Learn how to write multiline strings in Python. Discover different methods, tips, real-world applications, and how to debug common errors.

How to write a multiline string in Python
Published on: 
Tue
Mar 10, 2026
Updated on: 
Fri
Mar 13, 2026
The Replit Team

Python provides several ways to create strings that span multiple lines. This skill is essential for documentation, queries, and formatted text. It makes your code more readable and organized.

Here, you'll explore techniques to write multiline strings. You'll find practical tips, see real-world applications, and get advice to debug common issues and master this fundamental concept.

Using triple quotes for multiline strings

multiline_string = """This is a multiline string.
It can span multiple lines
without any special escape characters."""
print(multiline_string)--OUTPUT--This is a multiline string.
It can span multiple lines
without any special escape characters.

Using triple quotes—either """ or '''—is Python's most idiomatic way to define a string that spans multiple lines. The key advantage is that it preserves whitespace, including the line breaks you see in your editor. This makes your code cleaner and more readable, especially for:

  • Docstrings that explain functions or modules
  • Long SQL or GraphQL queries
  • Blocks of formatted text like poems or messages

The code assigns this formatted text to the multiline_string variable, and the output confirms the newlines are retained without needing any special escape characters.

Basic multiline string techniques

While triple quotes are the most common approach, you can also use string concatenation and backslashes to achieve similar results in different contexts.

Using triple single quotes (''')

multiline_string = '''Another way to create
multiline strings is with
triple single quotes.'''
print(multiline_string)--OUTPUT--Another way to create
multiline strings is with
triple single quotes.

Using triple single quotes (''') works just like using triple double quotes. It's mostly a matter of style which one you choose, as both preserve newlines and whitespace exactly as you type them.

  • The main advantage comes from convenience. If your string contains double quotes, you can wrap it in ''' without needing to escape them.

This simple trick keeps your code clean, especially when dealing with text that includes quoted dialogue or attributes.

Concatenating strings with the + operator

multiline_string = "First line.\n" + \
                 "Second line.\n" + \
                 "Third line."
print(multiline_string)--OUTPUT--First line.
Second line.
Third line.

You can also build multiline strings by joining smaller strings with the + operator. This method requires you to explicitly add newline characters (\n) where you want breaks. The backslash (\) at the end of each line simply tells Python that your code statement continues on the next line, which helps keep it organized.

  • This approach is useful when you're constructing a string dynamically from different parts, but it's less clean than triple quotes for static text.

Using line continuation with backslash

multiline_string = "This is a multiline string \
created using line continuation. \
The output will be on a single line."
print(multiline_string)--OUTPUT--This is a multiline string created using line continuation. The output will be on a single line.

Using a backslash (\) lets you break a long line of code across multiple lines for readability. Unlike triple quotes, it doesn't actually create a multiline string. Python simply ignores the line break and joins the parts into a single line of text.

  • This method is purely for formatting your source code—the final string won't contain any newlines unless you explicitly add them with \n.

Advanced multiline string techniques

With the basics down, you can now tackle more advanced challenges like managing indentation, embedding expressions, and handling special characters.

Using textwrap.dedent() for proper indentation

import textwrap

multiline_string = textwrap.dedent("""
   This multiline string
   will have consistent indentation
   thanks to textwrap.dedent()
""").strip()
print(multiline_string)--OUTPUT--This multiline string
will have consistent indentation
thanks to textwrap.dedent()

When you indent a multiline string to align with your code, Python includes that whitespace in the final string. The textwrap.dedent() function is the perfect tool to fix this. It automatically removes any common leading whitespace from every line in the text.

  • This lets you keep your source code neatly indented without affecting the string's final output.
  • Chaining .strip() at the end is a common practice that removes any blank lines from the beginning or end of your string.

Using f-strings for formatted multiline content

name = "Python"
version = 3.9
multiline_string = f"""
Welcome to {name}!
You are using version {version}
Enjoy the multiline capabilities!
""".strip()
print(multiline_string)--OUTPUT--Welcome to Python!
You are using version 3.9
Enjoy the multiline capabilities!

F-strings, or formatted string literals, let you embed expressions directly inside multiline strings. Simply prefix the opening triple quotes with an f. Python will then evaluate any expressions inside curly braces, like {name}, and insert their values into the final string.

  • This technique is incredibly useful for creating dynamic templates, such as email bodies or configuration files, without resorting to clumsy string concatenation with the + operator.

Working with raw strings (r"") for special characters

path_example = r"""C:\Users\Name\Documents
C:\Program Files\Python
These paths keep their backslashes intact"""
print(path_example)--OUTPUT--C:\Users\Name\Documents
C:\Program Files\Python
These paths keep their backslashes intact

When you prefix a string with an r, you're creating a "raw" string. This tells Python to treat backslashes as literal characters instead of using them for escape sequences like \n. It's incredibly useful for text that contains lots of backslashes, such as Windows file paths or regular expressions.

  • Combining r with triple quotes gives you a raw multiline string. This approach preserves both the line breaks and the literal backslashes, just as you see in the path_example.

Move faster with Replit

Replit is an AI-powered development platform that transforms natural language into working applications. You can describe what you want to build, and its AI capabilities help bring your idea to life.

With the multiline string techniques you've learned, Replit Agent can build complete apps—with databases, APIs, and deployment—directly from your descriptions. It can turn these concepts into production-ready tools.

  • Build a dynamic document generator that uses f-strings to populate multiline email or report templates.
  • Create a configuration file validator that parses and formats multiline text blocks, like SQL queries or code snippets.
  • Deploy a command-line utility that cleans up indented text using textwrap.dedent().

Describe your next project, and let Replit Agent write, test, and deploy the code for you, all from your browser.

Common errors and challenges

Mastering multiline strings means knowing how to navigate common issues like tricky indentation, escaped characters, and nested quotes.

A frequent challenge is finding extra spaces at the start of each line in your output. This happens because Python's triple-quoted strings capture all whitespace, including the indentation you use to keep your code tidy. While this preserves formatting, it can mess up your string's alignment.

The cleanest fix is using the textwrap.dedent() function. It intelligently removes the common leading whitespace from every line, letting you indent your code for readability without affecting the final string's content.

Backslashes are essential in regular expressions, but they can cause headaches inside regular strings where they also act as escape characters. For example, a regex pattern like \section becomes a newline followed by section. You'd typically have to escape the backslash by writing it as \\section, which clutters your pattern.

Using a raw string by prefixing it with an r solves this problem. It tells Python to treat every backslash as a literal character, not an escape. This makes your regex patterns much cleaner and easier to debug, especially when they span multiple lines.

You'll eventually need to include quotes inside your multiline strings. But what happens when you need the same quotes you used to define the string, like including a docstring example that uses """ inside your own """-delimited string?

  • The easiest fix is to use the alternative triple quote style. If your text contains """, wrap the entire string in ''', and vice versa.
  • If you must use the same style, you can escape the inner quotes with a backslash (e.g., \"\"\"). However, this can make the string harder to read, so it's usually better to switch quote styles when you can.

Fixing unexpected indentation in """multiline strings"""

It's a common snag with triple-quoted strings: when you indent them to keep your code neat, Python includes that indentation in the final output. This often results in unwanted leading spaces that can break your text's formatting. The code below demonstrates this.

def get_help_text():
   return """
   This text will keep all indentation
   which may not be what you want.
   """
print(get_help_text())

Because the string inside the get_help_text() function is indented with the code, Python includes those extra spaces in the output. This throws off the text's alignment. The following example shows how to fix this behavior.

import textwrap

def get_help_text():
   return textwrap.dedent("""
   This text will have proper indentation
   after using textwrap.dedent()
   """)
print(get_help_text())

The solution is to wrap the string with the textwrap.dedent() function. This function inspects the string and removes any common leading whitespace from every line. As a result, you can indent your multiline string to match your code's structure without adding unwanted spaces to the output. This is especially useful when defining strings inside indented blocks, like functions or classes, where you need both readable code and clean output.

Using r"" for regex patterns with backslashes

Backslashes in regular expressions can be a headache. Python's standard strings treat them as escape characters, forcing you to write \\ for every literal backslash. This clutters your pattern and makes it easy to introduce bugs that are hard to spot.

The following code shows how this can cause a regex pattern to fail.

import re

text = "File path: C:\\Users\\Documents\\file.txt"
pattern = "C:\\Users\\\\w+\\\\w+\\.txt"
match = re.search(pattern, text)
print(match)  # None - pattern is incorrect

The pattern fails due to over-escaping. The sequence \\\\w+ makes the regex engine look for a literal backslash followed by "w"s, not for word characters as \w+ intends. The corrected code below demonstrates the proper approach.

import re

text = "File path: C:\\Users\\Documents\\file.txt"
pattern = r"C:\\Users\\\w+\\\w+\.txt"
match = re.search(pattern, text)
print(match)  # Now matches correctly

The fix is to use a raw string by adding an r before the opening quote. This tells Python to treat backslashes as literal characters instead of escape sequences. The regex pattern r"C:\\Users\\\w+\\\w+\.txt" now works because \w+ is correctly interpreted as a sequence of word characters.

  • Always use raw strings for regex patterns to avoid escaping issues, especially with file paths or character classes like \d or \s.

Handling nested quotes in multiline strings

It's common to need quotes inside your multiline strings, but you'll run into trouble when they match the quotes defining the string itself. For instance, including double quotes inside a """ block can trigger a syntax error. The code below demonstrates this issue.

html = """
<button onclick="alert("Click me!")">Click</button>
"""
print(html)  # SyntaxError: invalid syntax

The SyntaxError occurs because the inner double quotes in the onclick attribute conflict with the outer """ delimiters. This confuses Python, which can't determine where the string actually ends. See how to resolve this in the corrected example below.

html = """
<button onclick="alert('Click me!')">Click</button>
"""
print(html)  # Using different quote types solves the problem

The fix is simple: use a different quote style inside your string. Since the html variable was defined with triple double quotes ("""), the onclick attribute now uses single quotes ('Click me!'). This avoids the syntax error by clearly separating the string's content from its delimiters.

You'll often encounter this when working with HTML, JSON, or any text that naturally includes quotation marks. Alternating between single and double quotes is the cleanest solution.

Real-world applications

Now that you can handle common challenges, you can use multiline strings for practical tasks like parsing configuration files and building SQL queries.

Creating a simple configuration file parser with parse_config()

Multiline strings are perfect for holding configuration data, which you can then process with a custom function like parse_config() to turn it into a structured dictionary.

def parse_config(config_string):
   config = {}
   for line in config_string.strip().split('\n'):
       if line and not line.startswith('#'):
           key, value = line.split('=')
           config[key.strip()] = value.strip()
   return config

config_text = """
# Database configuration
db_host=localhost
db_port=5432
db_name=myapp
"""

config = parse_config(config_text)
print(config)

The parse_config() function processes a multiline string by breaking it down line by line. It splits the text into a list, then loops through each line to extract key-value pairs.

  • It's designed to ignore empty lines and comments that start with a #.
  • For each valid line, it uses split('=') to separate the key from its value.
  • The function then stores the cleaned key and value in a dictionary.

The final print() call displays this dictionary, which neatly organizes the configuration data from the original string.

Building SQL queries with build_select_query()

Multiline f-strings are also perfect for building database queries on the fly, letting you piece together a final SQL statement from different variables.

def build_select_query(table, columns, conditions=None):
   query = f"""
SELECT {', '.join(columns)}
FROM {table}"""
   if conditions:
       query += f"""
WHERE {' AND '.join(conditions)}"""
   return query.strip()

columns = ["id", "name", "email"]
conditions = ["status = 'active'", "created_at > '2023-01-01'"]
query = build_select_query("users", columns, conditions)
print(query)

The build_select_query function dynamically assembles a SQL query using multiline f-strings. It's a clean way to build database commands without messy string concatenation.

  • It starts with the base SELECT and FROM clauses, using ', '.join(columns) to format the column list correctly.
  • If you pass in any conditions, it conditionally adds a WHERE clause, linking each condition with AND.

This approach makes the function flexible, allowing you to create simple or complex queries from the same template. The final string is tidied up with .strip().

Get started with Replit

Turn your knowledge into a tool. Give Replit Agent a prompt like "Build a Python script that cleans up indented text using textwrap.dedent()" or "Create a tool that generates SQL queries with multiline f-strings."

Replit Agent writes the code, tests for errors, and deploys the app directly from your description. Start building with Replit.

Get started free

Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.

Get started for free

Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.