Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Importing Multiple Files in Python
Next article icon

Break a long line into multiple lines in Python

Last Updated : 31 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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 geeks 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
geeks'''
 
y = """Geeks for geeks"""
 
x1 = '''Geeks for geeks'''
 
y1 = """Geeks for geeks"""
 
print(x==y)
print(x1==y1)
                      
                       

Output:

False True


Next Article
Importing Multiple Files in Python

V

vanshikagoyal43
Improve
Article Tags :
  • Python
  • Technical Scripter
  • python-basics
  • Technical Scripter 2020
Practice Tags :
  • python

Similar Reads

  • Break a List into Chunks of Size N in Python
    The goal here is to break a list into chunks of a specific size, such as splitting a list into sublists where each sublist contains n elements. For example, given a list [1, 2, 3, 4, 5, 6, 7, 8] and a chunk size of 3, we want to break it into the sublists [[1, 2, 3], [4, 5, 6], [7, 8]]. Let’s explor
    3 min read
  • Read a file line by line in Python
    Python provides built-in functions for creating, writing, and reading files. Two types of files can be handled in Python, normal text files and binary files (written in binary language, 0s, and 1s). In this article, we are going to study reading line by line from a file. Example [GFGTABS] Python # O
    4 min read
  • Importing Multiple Files in Python
    Here, we have a task to import multiple files from a folder in Python and print the result. In this article, we will see how to import multiple files from a folder in Python using different methods. Import Multiple Files From a Folder in PythonBelow, are the methods of importing multiple files from
    2 min read
  • Break a list comprehension Python
    Python's list comprehensions offer a concise and readable way to create lists. While list comprehensions are powerful and expressive, there might be scenarios where you want to include a break statement, similar to how it's used in loops. In this article, we will explore five different methods to in
    2 min read
  • Interesting Fact about Python Multi-line Comments
    Multi-line comments(comments block) are used for description of large text of code or comment out chunks of code at the time of debugging application.Does Python Support Multi-line Comments(like c/c++...)? Actually in many online tutorial and website you will find that multiline_comments are availab
    3 min read
  • How to input multiple values from user in one line in Python?
    The goal here is to take multiple inputs from the user in a single line and process them efficiently, such as converting them into a list of integers or strings. For example, if the user enters 10 20 30 40, we want to store this as a list like [10, 20, 30, 40]. Let’s explore different approaches to
    2 min read
  • Count number of lines in a text file in Python
    Counting the number of characters is important because almost all the text boxes that rely on user input have a certain limit on the number of characters that can be inserted. For example, If the file is small, you can use readlines() or a loop approach in Python. Input: line 1 line 2 line 3 Output:
    3 min read
  • How to Find the Longest Line from a Text File in Python
    Finding the longest line from a text file consists of comparing the lengths of each line to determine which one is the longest. This can be done efficiently using various methods in Python. In this article, we will explore three different approaches to Finding the Longest Line from a Text File in Py
    3 min read
  • How to Break a Function in Python?
    In Python, breaking a function allows us to exit from loops within the function. With the help of the return statement and the break keyword, we can control the flow of the loop. Using return keywordThis statement immediately terminates a function and optionally returns a value. Once return is execu
    3 min read
  • How to Add New Line in Dictionary in Python
    Dictionaries are key-value stores that do not inherently support formatting like new lines within their structure. However, when dealing with strings as dictionary values or when outputting the dictionary in a specific way, we can introduce new lines effectively. Let's explore various methods to add
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences