How to Create a Multiline String in Python for Beginners

How to Create a  Multiline String in Python for Beginners

Sometimes we have a very long string and we want to write it into multiple lines for better code readability. 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 string join() function in Python which is used to produce a string containing newlines.

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.

Create A Python Multiline String With Examples

Let’s now discuss each of these options in details. We have also provided examples with the description 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 second in 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)

It provides the following result:

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 PEP 8 guide recommends using brackets to create Python multiline string.

Backslash To Join String On Multiple Lines

It is a less preferred way to use backslash for line continuation. However, it certainly works and can join strings on various lines.

# 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 code gives the following result:


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.

Join() Method To Create A String With Newlines

The final approach is applying the string join() function to convert a string into multiline. It handles the space characters itself while contaminating the strings.

# 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.


# 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)

The result is:


I'm learning Python.
I refer to TechBeamers.com tutorials.
It is the most popular site for Python programmers.

We hope that after wrapping up this tutorial, you should feel comfortable in using Python multiline string. However, you may practice more with examples to gain confidence.

Thanks for reading !

python

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Basic Data Types in Python | Python Web Development For Beginners

In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.

How To Compare Tesla and Ford Company By Using Magic Methods in Python

Magic Methods are the special methods which gives us the ability to access built in syntactical features such as ‘<’, ‘>’, ‘==’, ‘+’ etc.. You must have worked with such methods without knowing them to be as magic methods. Magic methods can be identified with their names which start with __ and ends with __ like __init__, __call__, __str__ etc. These methods are also called Dunder Methods, because of their name starting and ending with Double Underscore (Dunder).

Python Programming: A Beginner’s Guide

Python is an interpreted, high-level, powerful general-purpose programming language. You may ask, Python’s a snake right? and Why is this programming language named after it?

Hire Python Developers

Are you looking for experienced, reliable, and qualified Python developers? If yes, you have reached the right place. At **[HourlyDeveloper.io](https://hourlydeveloper.io/ "HourlyDeveloper.io")**, our full-stack Python development services...

Python any: How to Check If Element is Iterable or Not

Python any() function returns True if any element of an iterable is True otherwise any() function returns False. The syntax is any().