Wrap Long Lines in Python



In Python, we will come across situations where we encounter long lines of code that exceed the recommended line length of 79 characters (suggested by the Python style guide).

To improve code readability, Python provides several ways to wrap long lines. In this article, we will explore the various methods to wrap long lines in Python.

Using Backslash(\)

The Backslash(\) is used as the line continuation character in Python. It indicates the compiler that the statement continues on the next line. If we try to place anything (word, space or comment) after the backslash, it will result in a syntax error.

Example 1

Let's look at the following example, where we are going to use the backslash and observe the output.

demo = 112 + 234 + 21 + 222 + 312 + \
               564 + 234
print("Result :", demo)

The output of the above program is as follows -

Result : 1699

Example 2

Consider another scenario, where we are going to place the space after the backslash and observe the output.

str1 = "Hi, " + "Welcome " + "to " + \ 
       "TutorialsPoint "
print("Result:", str1)

The output of the above program is as follows -

SyntaxError: unexpected character after line continuation character

Using Parentheses

Python allows the implicit line continuation inside the parentheses(), brackets[], and curly braces{}. It is preferred over the backslash as it is less error-prone. We can break a long list, tuples, or dictionary across multiple lines without the need for any special character.

Example

In the following example, we are going to wrap a list across multiple lines using the brackets.

str1 = ["Hi", "Hello", "Vanakam"]
print("Result :", str1)

The output of the above program is as follows -

Cars: Ciaz, Buggati and Audi

Using Python textwrap.fill() Function

In this approach, we are going to use the Python textwrap module, which provides the functionality for formatting and wrapping plain text. The textwrap.fill() function accepts a long string and wraps it, making each line at the specified width.

Syntax

Following is the syntax of the Python textwrap.fill() function -

textwrap.fill(text, width)

Example

Following is an example where we are going to use the textwrap module and wrap the lines -

import textwrap
str1 = "Welcome to the TutorialsPoint, The E-learning Platform."  
result = textwrap.fill(str1, width=12)
print(result)

The output of the above program is as follows -

Welcome to
the Tutorial
sPoint, The
E-learning
Platform.
Updated on: 2025-05-20T13:01:25+05:30

22K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements