Multi-line Statements in Python: Breaking Code Across Lines (line continuation techniques)


If you have a statement in Python that is too long and you want to break that statement into multiple lines without breaking the indentation rule of Python, then you need to take a look at the PEP 8 which is titled "Style Guide for Python Code"

PEP 8 suggests a maximum line length of 79 characters for code readability. a line exceeds this limit, it should be broken into multiple lines.

To break a line without breaking the indentation rule, you can use line continuation techniques.


Example:

Let's say we have a string with a concatenation of a few strings.

my_data = "This is some text" + " that is too long " + " and breaks readability" + " as it spans over 79 characters."+ " Lets try to fix it"

We can make use of below-line continuation techniques

Option 1: Using parentheses for line continuation


my_data = ("This is some text" +
           " that is too long " +
           " and breaks readability" +
           " as it spans over 79 characters." +
           " Let's try to fix it")

Option 2: Using backslashes for line continuation


my_data = "This is some text" + \
          " that is too long " + \
          " and breaks readability" + \
          " as it spans over 79 characters." + \
          " Let's try to fix it"

Option 3: Implicit line continuation (no plus sign needed)


my_data = "This is some text" \
          " that is too long " \
          " and breaks readability" \
          " as it spans over 79 characters." \
          " Let's try to fix it"

Example:
>>> my_data = "This is some text" \
...           " that is too long " \
...           " and breaks readability" \
...           " as it spans over 79 characters." \
...           " Let's try to fix it"
>>> print(my_data)
This is some text that is too long and breaks readability as it spans over 79 characters. Let's try to fix it
>>> 
line continuation technique Python

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright Β© Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap