![]() |
|
[Tut] Python One Line to Multiple Lines - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Python One Line to Multiple Lines (/thread-96823.html) |
[Tut] Python One Line to Multiple Lines - xSicKxBot - 08-21-2020 Python One Line to Multiple Lines 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: \After publishing an article on how to condense multiple lines into a single line of Python code, many Finxters asked: How to break a long line to multiple lines in Python? This article shows you the best way of breaking a long-winded one-liner into multiple lines to improve readability and unclutter your code. Problem: Given a long line of Python code. How to break it into multiple lines? There are multiple ways of breaking this into multiple lines. Let’s get an overview first: https://trinket.io/embed/python/cce7ca4ab8 Exercise: Run the code. What’s the output? Modify Method 3 and write it as a one-liner again! We now dive into each of those methods. Method 1: Implicit Line Continuation — Use Parentheses to Avoid Line Break Backslashes ![]() The PEP 8 – Style Guide 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. Here’s the original statement from the PEP 8 style guide (emphasis by me): Quote:The preferred way of wrapping long lines is by using Python’s implied line continuation inside parentheses, brackets and braces. If necessary, you can add an extra pair of parentheses around an expression, but sometimes using a backslash looks better. Make sure to indent the continued line appropriately. Do you need an example for implicit line continuation? Here it is: Code: # 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)]The long line Code: a = list(zip(['Alice', 'Bob', 'Liz', 'Ann'], [18, 24, 19, 16]))Code: [('Alice', 18), ('Bob', 24), ('Liz', 19), ('Ann', 16)]Code: bRemember: you can always break lines if an opened bracket, parenthesis, or bracelet has not been closed! Method 2: Explicit Line Continuation — Use the Line Break Backslash \ 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? The answer is: yes! Just use the line break backslash Code: \Here’s a minimal example that shows the flexibility with which you can break new lines this way: Code: a = 1 + 2 + 3 + 4 - 5 * 2 b = 1 \ + 2 + \ 3 + 4\ - 5 *\ 2 print(a)
# 0 print(b)
# 0Seeing the messy code in the previous example may cause you to ask: Should a Line Break Before or After a Binary Operator? I’ll give the following answer based on the PEP 8 Style Guide (highlights by me): For decades the recommended style was to break after binary operators. But this can hurt readability in two ways:
Here, the eye has to do extra work to tell which items are added and which are subtracted: Code: # Wrong:
results = (variable1 + variable2 + (variable3 - variable4) - variable5 - variable6)To solve this readability problem, mathematicians and their publishers follow the opposite convention. Donald Knuth explains the traditional rule in his Computers and Typesetting series: “Although formulas within a paragraph always break after binary operations and relations, displayed formulas always break before binary operations” [3]. Thus, the following code is proposed: Code: # Correct:
results = (variable1 + variable2 + (variable3 - variable4) - variable5 - variable6)You can do both in Python but you should prefer the latter to improve readability of your code! Method 3: Break a String by Using a Multi-Line String with Triple Quotes Example: Say, you have the following long string from Romeo and Juliet: Code: 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'Note the newline character in the string: it’s really a multip-line string! Can you rewrite this into multiple lines to improve readability? 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: 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)
# TrueThese are two ways of defining the same string. If you compare them, the result is Code: TrueWhere to Go From Here? Enough theory, let’s get some practice! 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? Practice projects is how you sharpen your saw in coding! Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people? 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. Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home. Join the free webinar now! |