Sunday, December 29, 2024
Google search engine
HomeLanguagesBreak a long line into multiple lines in Python

Break a long line into multiple lines in Python

Break a long line into multiple lines, in Python, is very important sometime for enhancing the readability of the code. Writing a really long line in a single line makes code appear less clean and there are chances one may confuse it to be complex.

Example: Breaking a long line of Python code into multiple lines

Long Line: a = 1 + 2 + 3 + 4 - 5 * 2

Multiple Lines:
a = (1 + 2) +\
    (3 + 4) -\
    (5 * 2) *\
    (6 * 3) +\
    (5 * 2 - 1)

Break a long line into multiple lines using backslash

A backslash(\) can be put between the line to make it appear separate, as shown below. Also, notice that all three cases produce exactly the same output, the only difference is in the way they are presented in the code.

Example: Breaking a long string (>79 chars) into multiple lines.

According to PEP8 coding convention, each line should be limited to maximum 79 characters for better readability. Here we are trying to achieve that by either using backslash(\) or by separating string in multiple blocks inside a statement.

Python3




# complete string in a single line
print("BEFORE BREAKING:")
print("How many times were you frustrated \
while looking out for a good collection of\
programming/ algorithm/ interview questions?")
 
print()
print("AFTER BREAKING:")
# in print() statement adding backslash(\) is redundant
print("How many times were you frustrated while looking out "
      "for a good collection of programming/ algorithm/ "
      "interview questions?")
 
 
print("\nAFTER STORING IN A VARIABLE:")
# while storing the same string in a variable adding backslash is required
line = "How many times were you frustrated while looking out for a good " \
       "collection of programming/ algorithm/ interview questions?"
print(line)


Output:

BEFORE BREAKING:

How many times were you frustrated while looking out for a good collection of programming/ algorithm/ interview questions?

AFTER BREAKING:

How many times were you frustrated while looking out for a good collection of programming/ algorithm/ interview questions?

AFTER STORING IN A VARIABLE:

How many times were you frustrated while looking out for a good collection of programming/ algorithm/ interview questions?

Break a long line into multiple lines using the string concatenation operator

The string concatenation operator (+), something so basic, can easily replace backslashes in the above example to give out the same output.

Example: Using + operator to write long strings in multiple lines inside print() method

Python3




print("How many times were you" +
      " frustrated while looking" +
      " out for a good collection" +
      " of programming/ algorithm/" +
      "interview questions? What" +
      " did you expect and what " +
      "did you get? Geeks for gee" +
      "ks is a portal that has bee" +
      "n created to provide well wr" +
      "itten, well thought and wel" +
      "l explained solutions for se" +
      "lected questions.")


Output:

How many times were you frustrated while looking out for a good collection of programming/ algorithm/interview questions? What did you expect and what did you get? Geeks for Lazyroar is a portal that has been created to provide well written, well thought and well explained solutions for selected questions.

Break a long line into multiple lines using parenthesis

The same output can be achieved by keeping each fragment in parentheses and separating each fragment from the other using a comma(,).

Example: Breaking long line of Python code into multiple line using parenthesis ()

Here, we have used parenthesis to break a long if statement into multiple lines.

Python3




string = """Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
est laborum. """
 
if ((string[:10].count('a') > 5 and string[10:].count('e') > 3 and
     string.count('v') >= 5) or len(set(string)) > 26):
    print("Our condition matched!")


Output:

Our condition matched!

Comparing three double quotes and three single quotes 

In this example, we will try to compare the 2 multiline strings in Python, to check if both are the same or not. As in the output, we can see that we are getting False because there’s a newline character (\n) in x, whereas in y there is no newline character.

Python3




x = '''Geeks
for
Lazyroar'''
 
y = """Geeks for Lazyroar"""
 
x1 = '''Geeks for Lazyroar'''
 
y1 = """Geeks for Lazyroar"""
 
print(x==y)
print(x1==y1)


Output:

False
True

RELATED ARTICLES

Most Popular

Recent Comments