The common way is the format() function:

>>> s = "This is an {example} with {vars}".format(vars="variables", example="example")
>>> s
'This is an example with variables'

It works fine with a multi-line format string:

>>> s = '''\
... This is a {length} example.
... Here is a {ordinal} line.\
... '''.format(length='multi-line', ordinal='second')
>>> print(s)
This is a multi-line example.
Here is a second line.

You can also pass a dictionary with variables:

>>> d = { 'vars': "variables", 'example': "example" }
>>> s = "This is an {example} with {vars}"
>>> s.format(**d)
'This is an example with variables'

The closest thing to what you asked (in terms of syntax) are template strings. For example:

>>> from string import Template
>>> t = Template("This is an $example with $vars")
>>> t.substitute({ 'example': "example", 'vars': "variables"})
'This is an example with variables'

I should add though that the format() function is more common because it's readily available and it does not require an import line.

Answer from Simeon Visser on Stack Overflow
Top answer
1 of 10
282

The common way is the format() function:

>>> s = "This is an {example} with {vars}".format(vars="variables", example="example")
>>> s
'This is an example with variables'

It works fine with a multi-line format string:

>>> s = '''\
... This is a {length} example.
... Here is a {ordinal} line.\
... '''.format(length='multi-line', ordinal='second')
>>> print(s)
This is a multi-line example.
Here is a second line.

You can also pass a dictionary with variables:

>>> d = { 'vars': "variables", 'example': "example" }
>>> s = "This is an {example} with {vars}"
>>> s.format(**d)
'This is an example with variables'

The closest thing to what you asked (in terms of syntax) are template strings. For example:

>>> from string import Template
>>> t = Template("This is an $example with $vars")
>>> t.substitute({ 'example': "example", 'vars': "variables"})
'This is an example with variables'

I should add though that the format() function is more common because it's readily available and it does not require an import line.

2 of 10
98

You can use Python 3.6's f-strings for variables inside multi-line or lengthy single-line strings. You can manually specify newline characters using \n.

Variables in a multi-line string

string1 = "go"
string2 = "now"
string3 = "great"

multiline_string = (
    f"I will {string1} there\n"
    f"I will go {string2}.\n"
    f"{string3}."
)

print(multiline_string)

I will go there
I will go now
great

Variables in a lengthy single-line string

string1 = "go"
string2 = "now"
string3 = "great"

singleline_string = (
    f"I will {string1} there. "
    f"I will go {string2}. "
    f"{string3}."
)

print(singleline_string)

I will go there. I will go now. great.


Alternatively, you can also create a multiline f-string with triple quotes where literal newlines are considered part of the string. However, any spaces at the start of the line would also be part of the string, so it can mess with code indentation.

multiline_string = f"""I will {string1} there.
I will go {string2}.
{string3}."""
🌐
Reddit
reddit.com › r/learnpython › format or interpolate a multi-line string?
r/learnpython on Reddit: Format or interpolate a multi-line string?
April 12, 2019 -

Hey everyone I'm using Python 3 and am pretty new to Python in general. I'm having trouble formatting a multi-line string. I tried prefixing with f as well as just calling .format(variableName) at the end. The f-string variant triggers an invalid syntax error and the .format variant triggers a KeyError.

Is it possible to interpolate variables into a multi-line string? I know old-school string concatenation works, but that has its drawbacks on readability (at least).

Edit: Thanks for the responses! I ended up figuring out that I had curly braces in my string that weren't doubled up. facepalm

Discussions

How to do multi-line f strings?
My config: Python 3.9, Pycharm CE 2023.3.2, on Windows 10 Pro. I’m using Qt Designer and pyuic6 6.4.2. I’m new to Python and have not yet completed a 62 hour tutorial on Python. (I’m using Python 3.9 for the long tutorial I’m doing. I will upgrade Python later.) More on discuss.python.org
🌐 discuss.python.org
19
0
February 22, 2024
Is there any way to use variables in multiline string in Python? - Stack Overflow
You appear to want a multi-line String, not a multi-line comment. Using a variable in a comment wouldn't make any sense - comments aren't executed. ... Python doesn't have multi-line comments. Triple-quoted strings are not comments. ... That's right. Sorry. Multiline strings. I'm new into python. More on stackoverflow.com
🌐 stackoverflow.com
March 9, 2016
Concatenate strings in python in multiline - Stack Overflow
How can I do a line break (line continuation) in Python (split up a long line of source code)? (11 answers) How do I put a variable’s value inside a string (interpolate it into the string)? (9 answers) Closed 3 years ago. I have some strings to be concatenated and the resultant string will be quite long. I also have some variables to be concatenated. How can I combine both strings and variables so the result would be a multiline ... More on stackoverflow.com
🌐 stackoverflow.com
Python: format multitline strings with variables - Stack Overflow
I'm writing a Python script at work that contains a part with a large multiline string that also needs to expand variables. I'm used to doing it the following way in Python 2.6 or Python 3: messag... More on stackoverflow.com
🌐 stackoverflow.com
🌐
W3Schools
w3schools.com › python › gloss_python_multi_line_strings.asp
Python Multiline Strings
Note: in the result, the line breaks are inserted at the same position as in the code. Python Strings Tutorial String Literals Assigning a String to a Variable Strings are Arrays Slicing a String Negative Indexing on a String String Length Check In String Format String Escape Characters
🌐
Educative
educative.io › answers › how-to-assign-a-multiline-string-to-a-variable-in-python
How to assign a multiline string to a variable in Python
To create a multiline string variable in a Python code, to avoid an error message, we enclose the multiline string in three single quotes ('''Multiline string''') or three double quotes (""" Multiline string""")
🌐
Quora
quora.com › How-can-I-assign-a-multi-line-string-to-a-variable-in-Python
How to assign a multi-line string to a variable in Python - Quora
Answer (1 of 5): by using “““ ””” triple quotes using your_variable = “““ enter your multi line string ”””
🌐
TechBeamers
techbeamers.com › python-multiline-string
Python Multiline String - TechBeamers
November 30, 2025 - """ print(multiline_str) ... Supports dynamic content insertion. Modern and concise formatting method. The string format() method is a simple way to insert variables into multiline strings.
Find elsewhere
Top answer
1 of 4
144

There are several ways. A simple solution is to add parenthesis:

strz = ("This is a line" +
       str1 +
       "This is line 2" +
       str2 +
       "This is line 3")

If you want each "line" on a separate line you can add newline characters:

strz = ("This is a line\n" +
       str1 + "\n" +
       "This is line 2\n" +
       str2 + "\n" +
       "This is line 3\n")
2 of 4
54

Python 3: Formatted Strings

As of Python 3.6 you can use so-called "formatted strings" (or "f strings") to easily insert variables into your strings. Just add an f in front of the string and write the variable inside curly braces ({}) like so:

>>> name = "John Doe"
>>> f"Hello {name}"
'Hello John Doe'

To split a long string to multiple lines surround the parts with parentheses (()) or use a multi-line string (a string surrounded by three quotes """ or ''' instead of one).

1. Solution: Parentheses

With parentheses around your strings you can even concatenate them without the need of a + sign in between:

a_str = (f"This is a line \n{str1}\n"
         f"This is line 2 \n{str2}\n"
         f"This is line 3")  # no variable in this line, so a leading f"" is optional but can be used to properly align all lines

Good to know: If there is no variable in a line, there is no need for a leading f for that line.

Good to know: You could achieve the same result with backslashes (\) at the end of each line instead of surrounding parentheses but accordingly to PEP8 you should prefer parentheses for line continuation:

Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.

2. Solution: Multi-Line String

In multi-line strings you don't need to explicitly insert \n, Python takes care of that for you:

a_str = f"""This is a line
        {str1}
        This is line 2
        {str2}
        This is line 3"""

Good to know: Just make sure you align your code correctly otherwise you will have leading white space in front each line.


By the way: you shouldn't call your variable str because that's the name of the datatype itself.

Sources for formatted strings:

  • What's new in Python 3.6
  • PEP498
🌐
AskPython
askpython.com › home › 4 techniques to create python multiline strings
4 Techniques to Create Python Multiline Strings - AskPython
April 10, 2023 - While creating multiline strings using a backslash(\), the user needs to explicitly mention the spaces between the strings. ... inp_str = "You can find the entire set of tutorials for Python and R on JournalDev."\ "Adding to it, AskPython has got a very detailed version of Python understanding through its easy to understand articles."\ "Welcome to AskPython!!" print(inp_str)
🌐
DataCamp
datacamp.com › tutorial › python-string-interpolation
Python String Interpolation: A Beginner's Guide | DataCamp
February 13, 2025 - In this code, the output_string variable is assigned an f-string. The f prefix before the opening quote indicates that the string supports embedded expressions. The variable name is evaluated and its value is inserted into the string, resulting in the output: "My name is Mark."
🌐
DNMTechs
dnmtechs.com › creating-a-multiline-python-string-with-inline-variables-in-python-3
Creating a Multiline Python String with Inline Variables in Python 3 – DNMTechs – Sharing and Storing Technology Knowledge
This example demonstrates how to create a multiline string in Python using f-strings. The variables name, age, and city are inserted into the string using curly braces and the f prefix.
🌐
sqlpey
sqlpey.com › python › top-5-methods-to-create-multiline-strings-in-python-with-variables
Top 5 Methods to Create Multiline Strings in Python with Variables
November 6, 2024 - This utilizes Python’s ability to unpack local variables into the format string, resulting in: I will go there. I will go now. great · You can pass a dictionary to the format() method, allowing variable names to become keys that correspond to their values. variables = { 'string1': 'go', 'string2': 'now', 'string3': 'great' } multiline_string = '''I will {string1} there.
🌐
Glarity
askai.glarity.app › search › How-can-I-insert-variables-into-a-multi-line-string-in-Python
How can I insert variables into a multi-line string in Python? - Ask and Answer - Glarity
Answer: To insert variables into a multi-line string in Python, you can use several methods: 1. **Triple Quotes**: Enclose your string in triple quotes (`"""` or `'''`)
🌐
Delft Stack
delftstack.com › home › howto › python › python multi line string
How to Create a Multi Line String in Python | Delft Stack
February 2, 2024 - One way to create a multi-line string is to use """ at the start and end of the lines. Using triple quotes instead of single or double quotes, we can assign multi-line text to the string.
🌐
CodeRivers
coderivers.org › blog › python-multiline-string
Python Multiline Strings: A Comprehensive Guide - CodeRivers
January 20, 2025 - The f-string allows us to insert the variables directly into the string using curly braces ({}). The resulting output is a neatly formatted multiline string. When working with multiline strings, it's common to have leading or trailing whitespace (spaces, tabs, or newlines) that we may want ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › multiline-string-in-python
Multiline String in Python - GeeksforGeeks
July 23, 2025 - To better understand the Python ... to split a large string into a multiline Python string. Triple quotes (''' or """) can be used to create a multiline string....
🌐
Software Testing Material
softwaretestingmaterial.com › home › python › python multiline string
Python Multiline String - 5 Ways Explained with Examples
June 11, 2025 - Keeping all the text in a single line makes it difficult to read and looks clumsy. It gives better readability if you write it into multiple lines. Multiline String in python helps you to overcome this. Also, learn Strings in Python here. You can assign a multiline string to a variable in the ...
🌐
Reddit
reddit.com › r/learnpython › best way to add variable to multiline string
r/learnpython on Reddit: Best way to add variable to multiline string
May 22, 2018 -

I would like to do something like this:

import json
import random

string_device = '''
{
    "d": [
        {
            "deviceId": 1688642,
            "pounds": random.randint(100,500),
            "voltage": random.uniform(2.0, 6.0)
        }
    ]
 }

'''
data = json.loads(string_device)

for device in data['d']:
    print(device['voltage'], device['pounds'])

I need a string variable so I can call json.loads to create a json object. How do I add the random.randint and random.uniform calls within the multi-line string?

Thanks!