Python - How to break a long line into multiple lines

By xngo on June 14, 2019

When writting articles that include Python code, it is often needed to break a long line of code into multiple lines. This will improve readability of your articles on limited screen space devices such as laptops, tablets and smartphones.

Here are different ways to break down a long line of code into mutliple lines.

# Line break using backward slash(\)
long_string = "My favorite fruits are: " + \
                   "apple, "             + \
                   "banana and "         + \
                   "pineapple."
 
if a == True and \
   b == False:
    print("Do something")
 
# Line break using parentheses().
if (width == 0 and height == 0 and
        color == 'red' and emphasis == 'strong' or
        highlight > 100):
    print("Do something")        
 
# For function, you can just have arguments on the next line without any problems.
fct = myfunction(arg1,
                   arg2,
                   arg3)
# Similarly, you can do the same with list.
fruits = [ 'apple',
            'banana',
            'pineapple'
            ]
 

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.