This tutorial explains how to create a Python multiline string. It can be handy when you have a very long string. You shouldn’t keep such text in a single line. It kills the readability of your code.
In Python, you have different ways to specify a multiline string. You can have a string split across multiple lines by enclosing it in triple quotes. Alternatively, brackets can also be used to spread a string into different lines.
Moreover, backslash works as a line continuation character in Python. You can use it to join text on separate lines and create a multiline string. Finally, there is the string join() function in Python which is used to produce a string containing newlines.
Create a Python Multiline String with Examples
Let’s now discuss each of these options in detail. We have also provided examples with descriptions of every method.
Use triple quotes to create a multiline string
It is the simplest method to let a long string split into different lines. You will need to enclose it with a pair of Triple quotes, one at the start and the second at the end.

"""Learn Python Programming"""
Anything inside the enclosing Triple quotes will become part of one multiline string. Let’s have an example to illustrate this behavior.
# String containing newline characters line_str = "I'm learning Python.\nI refer to TechBeamers.com tutorials.\nIt is the most popular site for Python programmers."
Now, we’ll try to slice it into multiple lines using triple quotes.
# String containing newline characters line_str = "I'm learning Python.\nI refer to TechBeamers.com tutorials.\nIt is the most popular site for Python programmers." print("Long string with newlines: \n" + line_str) # Creating a multiline string multiline_str = """I'm learning Python. I refer to TechBeamers.com tutorials. It is the most popular site for Python programmers.""" print("Multiline string: \n" + multiline_str)
After running the above, the output is:
Long string with newlines: I'm learning Python. I refer to TechBeamers.com tutorials. It is the most popular site for Python programmers. Multiline string: I'm learning Python. I refer to TechBeamers.com tutorials. It is the most popular site for Python programmers.
This method retains the newline ‘\n’ in the generated string. If you want to remove the ‘\n’, then use the strip()/replace() function.
Use brackets to define a multiline string
Another technique is to enclose the slices of a string over multiple lines using brackets.

See the below example to know how to use it:
# Python multiline string example using brackets multiline_str = ("I'm learning Python. " "I refer to TechBeamers.com tutorials. " "It is the most popular site for Python programmers.") print(multiline_str)
After you run the above code, it prints the multiline line Python string as shown below.
I'm learning Python. I refer to TechBeamers.com tutorials. It is the most popular site for Python programmers.
You can see there is no newline character in the output. However, if you want it, then add it while creating the string.
# Python multiline string with newlines example using brackets multiline_str = ("I'm learning Python.\n" "I refer to TechBeamers.com tutorials.\n" "It is the most popular site for Python programmers.") print(multiline_str)
Here is the output after execution:
I'm learning Python. I refer to TechBeamers.com tutorials. It is the most popular site for Python programmers.
Please note that the PEP 8 guide recommends using brackets to create a Python multiline string.
Learning Python strings is interesting but it is also not a small topic to contain in just one tutorial. So, try to expand your reach to other related topics and keep learning.
Backslash to join string on multiple lines
It is a less preferred way to use a backslash for line continuation. However, it certainly works and can join strings on various lines.

Check out the below code:
# Python multiline string example using backslash multiline_str = "I'm learning Python. " \ "I refer to TechBeamers.com tutorials. " \ "It is the most popular site for Python programmers." print(multiline_str)
The above Python code prints the multiline string in the following manner:
I'm learning Python. I refer to TechBeamers.com tutorials. It is the most popular site for Python programmers.
You can observe that the output isn’t showing any newlines. However, you may like to add some by yourself.
# Python multiline string example using backslash and newlines multiline_str = "I'm learning Python.\n" \ "I refer to TechBeamers.com tutorials.\n" \ "It is the most popular site for Python programmers." print(multiline_str)
The output:
I'm learning Python. I refer to TechBeamers.com tutorials. It is the most popular site for Python programmers.
Python Join() method to create a string with newlines
The final approach is applying the string join() function to convert a string into a multiline Python string. It handles the space characters by itself while contaminating the strings.

See the below sample code using the Python join() and without the newline separator.
# Python multiline string example using string join() multiline_str = ' '.join(("I'm learning Python.", "I refer to TechBeamers.com tutorials.", "It is the most popular site for Python programmers.")) print(multiline_str)
It outputs the following result:
I'm learning Python. I refer to TechBeamers.com tutorials. It is the most popular site for Python programmers.
Here, in this Python example, we have the newline character appended with each line in the multiline strings.
# Python multiline string with newlines example using string join() multiline_str = ''.join(("I'm learning Python.\n", "I refer to TechBeamers.com tutorials.\n", "It is the most popular site for Python programmers.")) print(multiline_str)
And, when you run the above code, it prints each sentence in a separate line.
I'm learning Python. I refer to TechBeamers.com tutorials. It is the most popular site for Python programmers.
By the way, to master string manipulation, you must also go through our tutorial on string formatting in Python.
How to declare multiline strings with arguments
In Python, you can create multiline strings with arguments by using triple-quoted strings and incorporating placeholders for the arguments. Placeholders are typically filled using string formatting techniques like f-strings, string.format()
or %
formatting. Here’s how to declare a multiline string with arguments:
Using f-strings (Python 3.6 and later):
F-strings are a new and concise way to format strings in Python. You can read about it in detail from our blog. It makes it very easy to supply arguments in a multiline string.
For example, the following code declares a multiline string with two arguments:
variable1 = "World" variable2 = 42 multiline_string = f""" Hello, {variable1}! I am {variable2} years old. """ print(multiline_string)
Using string.format()
Another common way to set up arguments in multiline strings is by using the Python string format() method. Here, we pass the arguments to the format() function which fills in the placeholders at runtime. In order to know how to use it, check out the below example.
variable1 = "World" variable2 = 42 multiline_string = """ Hello, {}! I am {} years old. """.format(variable1, variable2) print(multiline_string)
Using %
to supply arguments in a string
In this method, you specify the % format specifiers such as %s or %d in the multiline string. For example, the below Python code passes two arguments, one is a string and another is a number.
variable1 = "World" variable2 = 42 multiline_string = """ Hello, %s! I am %d years old. """ % (variable1, variable2) print(multiline_string)
Search a multiline string in a text file in Python
Sometimes, you might have to find a multiline string in a text file and the line number at which the string exists. So, in order to understand this, let’s first define our problem statement.
Problem statement:
Search a text file for a multiline string and return the line number in Python.
Sample data:
sample_file.txt:
This is the first line of the text file.
This is the second line.
apple.
mango.
grapse.
banana.
And here's the last line.
Mutltiline string to find:
mango.
grapse.
Solution:
The following Python code can be used to search a text file for a multiline string and return the line number. Please note that it not only searches the text but also creates the text file. So, it is fully working code that you can straightway use and run.
def search_in_txt(txt_file, multiline_str): """Searches a text file for a multiline string and returns the line number. Args: txt_file: The path to the text file. multiline_str: The multiline string to search for. Returns: The line number of the first line of the multiline string, or None if the multiline string is not found in the text file. """ with open(txt_file, "r") as txt: lines = txt.readlines() multiline_str_lines = multiline_str.strip().split('\n') for line_num, line in enumerate(lines): if multiline_str_lines[0] in line: found = True for j in range(1, len(multiline_str_lines)): if line_num + j >= len(lines) or multiline_str_lines[j] not in lines[line_num + j]: found = False break if found: return line_num + 1 return None # Example usage: txt_file = "sample_file.txt" file_content = """This is the first line of the text file. This is the second line. apple. mango. grapse. banana. And here's the last line. """ # Create and write the content to the text file with open(txt_file, "w") as file: file.write(file_content) with open(txt_file, "r") as file: lines = file.readlines() # Print the content of the text file with line numbers print("++++++++++++++++++++") for line_num, line in enumerate(lines, start=1): print(f"Line {line_num}: {line.strip()}") print("++++++++++++++++++++\n") multiline_str = """ mango. grapse. """ line_num = search_in_txt(txt_file, multiline_str) if line_num is not None: print("The multiline string was found on line {}".format(line_num)) else: print("The multiline string was not found in the text file.")
Once you run the above code, it automatically creates a text file with the sample data. Before searching, it also prints the file content so that you can verify the file content. After that, it searches for the Python multiline string in the text file and prints its line number.
++++++++++++++++++++ Line 1: This is the first line of the text file. Line 2: This is the second line. Line 3: apple. Line 4: mango. Line 5: grapse. Line 6: banana. Line 7: And here's the last line. ++++++++++++++++++++ The multiline string was found on line 4
We suggest you not only run the above code but also make more changes to it and sample data. Running it with different data sets will help you sustain the learning.
Conclusion
We hope that after wrapping up this tutorial, you will feel comfortable using Python multiline strings. However, you may practice more with examples to gain confidence. In order to give you an extra boost, you can always refer to our 40 Python exercises for beginners. With these exercises, you can span your learning to different areas of Python.
Also, to learn Python from scratch to depth, read our step-by-step Python tutorial.