How do I create a multiline Python string with inline variables?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Python offers several ways to create multiline strings with embedded variables. The most modern and readable approach is f-strings with triple quotes (f"""..."""), available since Python 3.6. Older alternatives include str.format() with triple-quoted strings and the % operator. Each method handles multiline text and variable interpolation, but they differ in readability, safety, and flexibility. For most use cases, f-strings are the best choice.
F-Strings with Triple Quotes (Recommended)
F-strings evaluate expressions inside {} at runtime. Triple quotes (""" or ''') allow the string to span multiple lines. You can include any Python expression inside the braces — function calls, conditionals, arithmetic, and method calls.
str.format() with Triple Quotes
str.format() separates the template from the data, making it useful when the template is defined separately from where it is populated — for example, in a configuration file or a different module.
Percent (%) Formatting
% formatting is the oldest string interpolation method in Python. It works but is less readable than f-strings, especially with many variables. It uses C-style format specifiers (%s, %d, %f).
textwrap.dedent for Clean Indentation
When multiline strings are inside indented functions, textwrap.dedent() removes the common leading whitespace so the output is not indented. The \ after the opening """ prevents a leading blank line.
Template Strings (Safe for User Input)
Template strings are safer for user-provided templates because they do not execute arbitrary Python expressions. $$ produces a literal $ sign. Use safe_substitute() when not all variables may be available.
Joining Lines
For dynamic content where the number of lines varies, building a list and joining with "\n" is cleaner than concatenating strings or using multiple f-string lines.
Multiline Strings in Function Arguments
Python automatically concatenates adjacent string literals. Wrapping in parentheses creates a multiline expression without actually embedding newlines — useful for SQL queries or log messages that should be a single line.
Raw Strings with Variables
The rf"""...""" prefix combines raw strings (no backslash escaping) with f-string interpolation. This is useful for regex patterns where you need both literal backslashes and variable substitution.
Common Pitfalls
- Unintended leading whitespace: Triple-quoted strings inside indented code include the indentation in the string. Use
textwrap.dedent()to strip it, or use parenthesized string concatenation instead. - Curly braces in f-strings: To include a literal
{or}in an f-string, double it:f"dict = {{'key': {value}}}". A single{without a variable inside raisesSyntaxError. - Security with f-strings and user input: Never use f-strings to build SQL queries, shell commands, or HTML with user-provided data. Use parameterized queries,
shlex.quote(), or template engines instead. - Leading newline with triple quotes:
"""\\ntext"""has a blank first line. Use"""\\(backslash immediately after quotes) ortextwrap.dedentto avoid it. - Mixing format methods: Combining
%and.format()in the same string causesTypeErrororKeyError. Pick one method and use it consistently throughout each string.
Summary
- Use
f"""..."""(f-strings with triple quotes) for most multiline strings with variables - Use
str.format()when templates are defined separately from data - Use
textwrap.dedent()to remove leading whitespace from indented multiline strings - Use
string.Templatefor user-provided templates where arbitrary code execution is a risk - Use parenthesized string concatenation for single-line strings split across multiple code lines
- Never use f-strings to interpolate user input into SQL, shell commands, or HTML

