08-21-2020, 03:13 PM
Python One Line to Multiple Lines
<div><p class="has-pale-cyan-blue-background-color has-background">To break one line into multiple lines in Python, use an opening parenthesis in the line you want to break. Now, Python expects the closing parenthesis in one of the next lines and the expression is evaluated across line boundaries. As an alternative, you can also use the backslash <code>\</code> just in front of the line break to escape the newline character. </p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="How to Break One Line Into Multiple Lines in Python?" width="1400" height="788" src="https://www.youtube.com/embed/nJ2AlulCwtg?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p>After publishing an article on how to condense <a href="https://blog.finxter.com/how-to-execute-multiple-lines-in-a-single-line-python-from-command-line/" title="How to Execute Multiple Lines in a Single Line Python From Command-Line?" target="_blank" rel="noreferrer noopener">multiple lines into a single line</a> of Python code, many Finxters asked:<em> <a href="https://stackoverflow.com/questions/4172448/is-it-possible-to-break-a-long-line-to-multiple-lines-in-python" target="_blank" rel="noreferrer noopener">How to break a long line to multiple lines in Python</a></em>? This article shows you the best way of breaking a long-winded <a href="https://pythononeliners.com/" target="_blank" rel="noreferrer noopener" title="https://pythononeliners.com/">one-liner</a> into multiple lines to improve readability and unclutter your code.</p>
<p><strong>Problem</strong>: Given a long line of Python code. How to break it into multiple lines?</p>
<p>There are multiple ways of breaking this into multiple lines. Let’s get an overview first:</p>
<p> <iframe src="https://trinket.io/embed/python/cce7ca4ab8" width="100%" height="700" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> </p>
<p><em><strong>Exercise</strong>: Run the code. What’s the output? Modify Method 3 and write it as a one-liner again!</em></p>
<p>We now dive into each of those methods.</p>
<h2>Method 1: Implicit Line Continuation — Use Parentheses to Avoid Line Break Backslashes</h2>
<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img src="https://blog.finxter.com/wp-content/uploads/2020/08/breakMultipleLinesIntoSingleLine-1024x576.jpg" alt="Break a Long Line to Multiple Lines Python" class="wp-image-11989" width="768" height="432" srcset="https://blog.finxter.com/wp-content/uploads/2020/08/breakMultipleLinesIntoSingleLine-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uplo...00x169.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x432.jpg 768w, https://blog.finxter.com/wp-content/uplo...150x84.jpg 150w" sizes="(max-width: 768px) 100vw, 768px" /></figure>
</div>
<p>The <a href="http://www.python.org/dev/peps/pep-0008/" target="_blank" rel="noreferrer noopener">PEP 8 – Style Guide</a> argues that the best way to break long lines into multiple lines of code is to use implicit line continuation by using parentheses. An opening parenthesis signals to Python that the expression has not finished, yet. So, the Python interpreter keeps looking in the following line to close the currently open expression. This way, you can rewrite any Python one-liner to a multi-liner just by using one or more pairs of parentheses.</p>
<p>Here’s the original statement from the PEP 8 style guide (emphasis by me):</p>
<blockquote class="wp-block-quote">
<p>The preferred way of wrapping long lines is by using Python’s <strong>implied line continuation inside parentheses, brackets and braces</strong>. If necessary, you can <strong>add an extra pair of parentheses</strong> around an expression, but sometimes using a backslash looks better. Make sure to indent the continued line appropriately.</p>
</blockquote>
<p>Do you need an example for implicit line continuation? Here it is:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">
# Long Line
a = list(zip(['Alice', 'Bob', 'Liz', 'Ann'], [18, 24, 19, 16])) # Implicit Line Continuation
b = list(zip(['Alice', 'Bob', 'Liz', 'Ann'], [18, 24, 19, 16])) print(a)
# [('Alice', 18), ('Bob', 24), ('Liz', 19), ('Ann', 16)] print(b)
# [('Alice', 18), ('Bob', 24), ('Liz', 19), ('Ann', 16)]</pre>
<p>The long line <code>a = list(zip(['Alice', 'Bob', 'Liz', 'Ann'], [18, 24, 19, 16]))</code> <a href="https://blog.finxter.com/zip-unzip-python/" title="Zip & Unzip: How Does It Work in Python?" target="_blank" rel="noreferrer noopener">zips together</a> two lists to obtain the result <code>[('Alice', 18), ('Bob', 24), ('Liz', 19), ('Ann', 16)]</code>. You can rewrite this into multiple lines by using the existing parentheses. Note that it is good style to hierarchically align the lines in Python. In our example, the two <a href="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener" title="The Ultimate Guide to Python Lists">lists </a>are aligned when creating the multi-line statement to assign the variable <code>b</code>. </p>
<p><em><strong>Remember</strong>: you can always break lines if an opened bracket, parenthesis, or bracelet has not been closed!</em></p>
<h2>Method 2: Explicit Line Continuation — Use the Line Break Backslash \</h2>
<p>However, what if you don’t want to introduce new parentheses into your expression? Can you still break up a one-liner into multiple lines?</p>
<p>The answer is: yes! Just use the line break backslash <code>\</code> which you may call <em>explicit line continuation</em>. With the backslash, you can break at any position in your expression. Technically, the backslash character “<a href="https://blog.finxter.com/python-re-escape/" title="Python Re Escape" target="_blank" rel="noreferrer noopener">escapes</a>” the newline character that follows immediately afterwards. By escaping the newline character, it loses its meaning and Python simply ignores it. This way, you don’t have to introduce any new parentheses.</p>
<p>Here’s a minimal example that shows the flexibility with which you can break new lines this way:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">a = 1 + 2 + 3 + 4 - 5 * 2 b = 1 \ + 2 + \ 3 + 4\ - 5 *\ 2 print(a)
# 0 print(b)
# 0</pre>
<p>Seeing the messy code in the previous example may cause you to ask:</p>
<h3><a href="https://www.python.org/dev/peps/pep-0008/#id20" target="_blank" rel="noreferrer noopener">Should a Line Break Before or After a Binary Operator?</a></h3>
<p>I’ll give the following answer based on the PEP 8 Style Guide (highlights by me):</p>
<p><em>For decades the recommended style was to <strong>break after binary operators</strong>. But this can <strong>hurt readability</strong> in two ways: </em></p>
<ul>
<li><em>the operators tend to get scattered across different columns on the screen, and </em></li>
<li><em>each operator is moved away from its operand and onto the previous line. </em></li>
</ul>
<p><em>Here, the <strong>eye has to do extra work</strong> to tell which items are added and which are subtracted:</em></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Wrong:
results = (variable1 + variable2 + (variable3 - variable4) - variable5 - variable6)</pre>
<p><em>To solve this readability problem, mathematicians and their publishers follow the <strong>opposite convention</strong>. </em></p>
<p><em>Donald Knuth explains the traditional rule in his Computers and Typesetting series: <strong>“Although formulas within a paragraph always break after binary operations and relations, displayed formulas always break before binary operations”</strong> <a href="https://www.python.org/dev/peps/pep-0008/#id10">[3]</a>.</em></p>
<p>Thus, the following code is proposed:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Correct:
results = (variable1 + variable2 + (variable3 - variable4) - variable5 - variable6)</pre>
<p>You can do both in Python but you should prefer the latter to improve readability of your code!</p>
<h2>Method 3: Break a String by Using a Multi-Line String with Triple Quotes</h2>
<p><strong>Example</strong>: Say, you have the following long string from Romeo and Juliet:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">s = 'Mistress! what, mistress! Juliet! fast, I warrant her, she:\n Why, lamb! why, lady! fie, you slug-a-bed!\n Why, love, I say! madam! sweet-heart! why, bride!\n What, not a word? you take your pennyworths now;\n Sleep for a week; for the next night, I warrant'</pre>
<p>Note the newline character in the string: it’s really a multip-line string! Can you rewrite this into multiple lines to improve readability?</p>
<p>You can restructure strings by using the triple quotes that allows you to define a multi-line string without the newline character <code>'\n'</code> in the string. This significantly improves readability of multi-line strings! Here’s an example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">s1 = 'Mistress! what, mistress! Juliet! fast, I warrant her, she:\n Why, lamb! why, lady! fie, you slug-a-bed!\n Why, love, I say! madam! sweet-heart! why, bride!\n What, not a word? you take your pennyworths now;\n Sleep for a week; for the next night, I warrant' # MULTI-LINE
s2 = '''Mistress! what, mistress! Juliet! fast, I warrant her, she: Why, lamb! why, lady! fie, you slug-a-bed! Why, love, I say! madam! sweet-heart! why, bride! What, not a word? you take your pennyworths now; Sleep for a week; for the next night, I warrant''' print(s1 == s2)
# True
</pre>
<p>These are two ways of defining the same string. If you compare them, the result is <code>True</code>. However, the second way is far more readable and should be preferred!</p>
<h2>Where to Go From Here?</h2>
<p>Enough theory, let’s get some practice!</p>
<p>To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?</p>
<p><strong>Practice projects is how you sharpen your saw in coding!</strong></p>
<p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?</p>
<p>Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.</p>
<p>Join my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and watch how I grew my coding business online and how you can, too—from the comfort of your own home.</p>
<p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p>
</div>
https://www.sickgaming.net/blog/2020/08/...ple-lines/
<div><p class="has-pale-cyan-blue-background-color has-background">To break one line into multiple lines in Python, use an opening parenthesis in the line you want to break. Now, Python expects the closing parenthesis in one of the next lines and the expression is evaluated across line boundaries. As an alternative, you can also use the backslash <code>\</code> just in front of the line break to escape the newline character. </p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="How to Break One Line Into Multiple Lines in Python?" width="1400" height="788" src="https://www.youtube.com/embed/nJ2AlulCwtg?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p>After publishing an article on how to condense <a href="https://blog.finxter.com/how-to-execute-multiple-lines-in-a-single-line-python-from-command-line/" title="How to Execute Multiple Lines in a Single Line Python From Command-Line?" target="_blank" rel="noreferrer noopener">multiple lines into a single line</a> of Python code, many Finxters asked:<em> <a href="https://stackoverflow.com/questions/4172448/is-it-possible-to-break-a-long-line-to-multiple-lines-in-python" target="_blank" rel="noreferrer noopener">How to break a long line to multiple lines in Python</a></em>? This article shows you the best way of breaking a long-winded <a href="https://pythononeliners.com/" target="_blank" rel="noreferrer noopener" title="https://pythononeliners.com/">one-liner</a> into multiple lines to improve readability and unclutter your code.</p>
<p><strong>Problem</strong>: Given a long line of Python code. How to break it into multiple lines?</p>
<p>There are multiple ways of breaking this into multiple lines. Let’s get an overview first:</p>
<p> <iframe src="https://trinket.io/embed/python/cce7ca4ab8" width="100%" height="700" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> </p>
<p><em><strong>Exercise</strong>: Run the code. What’s the output? Modify Method 3 and write it as a one-liner again!</em></p>
<p>We now dive into each of those methods.</p>
<h2>Method 1: Implicit Line Continuation — Use Parentheses to Avoid Line Break Backslashes</h2>
<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img src="https://blog.finxter.com/wp-content/uploads/2020/08/breakMultipleLinesIntoSingleLine-1024x576.jpg" alt="Break a Long Line to Multiple Lines Python" class="wp-image-11989" width="768" height="432" srcset="https://blog.finxter.com/wp-content/uploads/2020/08/breakMultipleLinesIntoSingleLine-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uplo...00x169.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x432.jpg 768w, https://blog.finxter.com/wp-content/uplo...150x84.jpg 150w" sizes="(max-width: 768px) 100vw, 768px" /></figure>
</div>
<p>The <a href="http://www.python.org/dev/peps/pep-0008/" target="_blank" rel="noreferrer noopener">PEP 8 – Style Guide</a> argues that the best way to break long lines into multiple lines of code is to use implicit line continuation by using parentheses. An opening parenthesis signals to Python that the expression has not finished, yet. So, the Python interpreter keeps looking in the following line to close the currently open expression. This way, you can rewrite any Python one-liner to a multi-liner just by using one or more pairs of parentheses.</p>
<p>Here’s the original statement from the PEP 8 style guide (emphasis by me):</p>
<blockquote class="wp-block-quote">
<p>The preferred way of wrapping long lines is by using Python’s <strong>implied line continuation inside parentheses, brackets and braces</strong>. If necessary, you can <strong>add an extra pair of parentheses</strong> around an expression, but sometimes using a backslash looks better. Make sure to indent the continued line appropriately.</p>
</blockquote>
<p>Do you need an example for implicit line continuation? Here it is:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">
# Long Line
a = list(zip(['Alice', 'Bob', 'Liz', 'Ann'], [18, 24, 19, 16])) # Implicit Line Continuation
b = list(zip(['Alice', 'Bob', 'Liz', 'Ann'], [18, 24, 19, 16])) print(a)
# [('Alice', 18), ('Bob', 24), ('Liz', 19), ('Ann', 16)] print(b)
# [('Alice', 18), ('Bob', 24), ('Liz', 19), ('Ann', 16)]</pre>
<p>The long line <code>a = list(zip(['Alice', 'Bob', 'Liz', 'Ann'], [18, 24, 19, 16]))</code> <a href="https://blog.finxter.com/zip-unzip-python/" title="Zip & Unzip: How Does It Work in Python?" target="_blank" rel="noreferrer noopener">zips together</a> two lists to obtain the result <code>[('Alice', 18), ('Bob', 24), ('Liz', 19), ('Ann', 16)]</code>. You can rewrite this into multiple lines by using the existing parentheses. Note that it is good style to hierarchically align the lines in Python. In our example, the two <a href="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener" title="The Ultimate Guide to Python Lists">lists </a>are aligned when creating the multi-line statement to assign the variable <code>b</code>. </p>
<p><em><strong>Remember</strong>: you can always break lines if an opened bracket, parenthesis, or bracelet has not been closed!</em></p>
<h2>Method 2: Explicit Line Continuation — Use the Line Break Backslash \</h2>
<p>However, what if you don’t want to introduce new parentheses into your expression? Can you still break up a one-liner into multiple lines?</p>
<p>The answer is: yes! Just use the line break backslash <code>\</code> which you may call <em>explicit line continuation</em>. With the backslash, you can break at any position in your expression. Technically, the backslash character “<a href="https://blog.finxter.com/python-re-escape/" title="Python Re Escape" target="_blank" rel="noreferrer noopener">escapes</a>” the newline character that follows immediately afterwards. By escaping the newline character, it loses its meaning and Python simply ignores it. This way, you don’t have to introduce any new parentheses.</p>
<p>Here’s a minimal example that shows the flexibility with which you can break new lines this way:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">a = 1 + 2 + 3 + 4 - 5 * 2 b = 1 \ + 2 + \ 3 + 4\ - 5 *\ 2 print(a)
# 0 print(b)
# 0</pre>
<p>Seeing the messy code in the previous example may cause you to ask:</p>
<h3><a href="https://www.python.org/dev/peps/pep-0008/#id20" target="_blank" rel="noreferrer noopener">Should a Line Break Before or After a Binary Operator?</a></h3>
<p>I’ll give the following answer based on the PEP 8 Style Guide (highlights by me):</p>
<p><em>For decades the recommended style was to <strong>break after binary operators</strong>. But this can <strong>hurt readability</strong> in two ways: </em></p>
<ul>
<li><em>the operators tend to get scattered across different columns on the screen, and </em></li>
<li><em>each operator is moved away from its operand and onto the previous line. </em></li>
</ul>
<p><em>Here, the <strong>eye has to do extra work</strong> to tell which items are added and which are subtracted:</em></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Wrong:
results = (variable1 + variable2 + (variable3 - variable4) - variable5 - variable6)</pre>
<p><em>To solve this readability problem, mathematicians and their publishers follow the <strong>opposite convention</strong>. </em></p>
<p><em>Donald Knuth explains the traditional rule in his Computers and Typesetting series: <strong>“Although formulas within a paragraph always break after binary operations and relations, displayed formulas always break before binary operations”</strong> <a href="https://www.python.org/dev/peps/pep-0008/#id10">[3]</a>.</em></p>
<p>Thus, the following code is proposed:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Correct:
results = (variable1 + variable2 + (variable3 - variable4) - variable5 - variable6)</pre>
<p>You can do both in Python but you should prefer the latter to improve readability of your code!</p>
<h2>Method 3: Break a String by Using a Multi-Line String with Triple Quotes</h2>
<p><strong>Example</strong>: Say, you have the following long string from Romeo and Juliet:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">s = 'Mistress! what, mistress! Juliet! fast, I warrant her, she:\n Why, lamb! why, lady! fie, you slug-a-bed!\n Why, love, I say! madam! sweet-heart! why, bride!\n What, not a word? you take your pennyworths now;\n Sleep for a week; for the next night, I warrant'</pre>
<p>Note the newline character in the string: it’s really a multip-line string! Can you rewrite this into multiple lines to improve readability?</p>
<p>You can restructure strings by using the triple quotes that allows you to define a multi-line string without the newline character <code>'\n'</code> in the string. This significantly improves readability of multi-line strings! Here’s an example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">s1 = 'Mistress! what, mistress! Juliet! fast, I warrant her, she:\n Why, lamb! why, lady! fie, you slug-a-bed!\n Why, love, I say! madam! sweet-heart! why, bride!\n What, not a word? you take your pennyworths now;\n Sleep for a week; for the next night, I warrant' # MULTI-LINE
s2 = '''Mistress! what, mistress! Juliet! fast, I warrant her, she: Why, lamb! why, lady! fie, you slug-a-bed! Why, love, I say! madam! sweet-heart! why, bride! What, not a word? you take your pennyworths now; Sleep for a week; for the next night, I warrant''' print(s1 == s2)
# True
</pre>
<p>These are two ways of defining the same string. If you compare them, the result is <code>True</code>. However, the second way is far more readable and should be preferred!</p>
<h2>Where to Go From Here?</h2>
<p>Enough theory, let’s get some practice!</p>
<p>To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?</p>
<p><strong>Practice projects is how you sharpen your saw in coding!</strong></p>
<p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?</p>
<p>Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.</p>
<p>Join my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and watch how I grew my coding business online and how you can, too—from the comfort of your own home.</p>
<p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p>
</div>
https://www.sickgaming.net/blog/2020/08/...ple-lines/