Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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:
Different Input and Output Techniques in Python3
Next article icon

Python - Output Formatting

Last Updated : 16 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, output formatting refers to the way data is presented when printed or logged. Proper formatting makes information more understandable and actionable. Python provides several ways to format strings effectively, ranging from old-style formatting to the newer f-string approach.

Formatting Output using String Modulo Operator(%)

The string modulo operator (%) is one of the oldest ways to format strings in Python. It allows you to embed values within a string by placing format specifiers in the string. Each specifier starts with a % and ends with a character that represents the type of value being formatted.

Python
# string modulo operator(%)  print("Geeks : %2d, Portal : %5.2f" % (1, 05.333))   print("Total students : %3d, Boys : %2d" % (240, 120))   # print integer value  print("%7.3o" % (25))   # print octal value  print("%10.3E" % (356.08977))   # print exponential value 

Output
Geeks :  1, Portal :  5.33 Total students : 240, Boys : 120     031  3.561E+02 
Formatting Output using String Modulo Operator(%)
Output Formatting using Modulo Operator

There are several ways to format output using String Method in Python. 

Table of Content

  • Formatting Output using The Format Method
    • Advanced Usage with Positional and Named Parameters
  • Formatting Output using The String Method
  • Python's Format Conversion Rule

Formatting Output using The Format Method

The format() method was introduced in Python 2.6 to enhance string formatting capabilities. This method allows for a more flexible way to handle string interpolation by using curly braces {} as placeholders for substituting values into a string. It supports both positional and named arguments, making it versatile for various formatting needs. For Example - 

Example 1: Basic positional formatting demonstrates how values are substituted based on their order:

Python
# Positional formatting with format() method  # Using indexed placeholders for string formatting print("I love {0} for \"{1}!\"".format("Geeks", "Geeks"))  # {0} is replaced by the first argument 'Geeks' print("{0} and Portal".format("Geeks"))  # Formatting with placeholders, {0} replaced by 'Geeks' print("Portal and {0}".format("Geeks")) 

Output
I love Geeks for "Geeks!" Geeks and Portal Portal and Geeks 

In this example, {0} and {1} refer to the first and second argument provided to format(), respectively.

The following diagram with an example usage depicts how the format method works for positional parameters: 

Formatting Output using The Format Method
Output Formatting using Format method

Advanced Usage with Positional and Named Parameters

The format() method also supports detailed formatting options such as setting widths, alignment, number formatting and more, which can be extremely useful for creating tabulated data or reports.

Example 2: Here's how positional parameters along with a named argument are used to format numbers and text precisely:

Python
# Advanced formatting with positional and named arguments  # Mixing positional and named arguments template = "Number one portal is {0}, {1} and {other}." print(template.format("Geeks", "For", other="Geeks"))  # Format integers and floats with specified width and precision print("Geeks :{0:2d}, Portal :{1:8.2f}".format(12, 0.5534))  # Demonstrate order swapping and formatting precision print("Second argument: {1:3d}, first one: {0:8.2f}".format(47.42, 11))  # Using named arguments for clarity in complex formats print("Geeks: {a:5d}, Portal: {p:8.2f}".format(a=453, p=59.058)) 

Output
Number one portal is Geeks, For and Geeks. Geeks :12, Portal :    0.55 Second argument:  11, first one:    47.42 Geeks:   453, Portal:    59.06 

In this example:

  • {0:2d} and {1:8.2f} demonstrate number formatting where 2d specifies a two-digit integer and 8.2f specifies a floating-point number with two decimal places padded to a total width of eight characters.
  • Named arguments a and p are used for additional clarity and are referenced directly in the format string.

Formatting Output using String Method

Python's string methods such as str.center(), str.ljust() and str.rjust() provide straightforward ways to format strings by aligning them within a specified width. These methods are ideal for organizing textual data neatly in output without using more complex formatting tools.

Example:

Python
cstr = "I love geeksforgeeks"  # Printing the center aligned string with fillchr print("Center aligned: ") print(cstr.center(40, '#'))  # Printing the left aligned string with "-" padding print("left aligned: ") print(cstr.ljust(40, '-'))  # Printing the right aligned string with "-" padding print("right aligned: ") print(cstr.rjust(40, '-')) 

Output
Center aligned:  ##########I love geeksforgeeks########## left aligned:  I love geeksforgeeks-------------------- right aligned:  --------------------I love geeksforgeeks 

Format Conversion Rule

This table lists the standard format conversion guidelines used by Python's format() function.

Conversion

Meaning

d

Decimal integer

b

Binary format

o

octal format

u

Obsolete and equivalent to 'd'

x or X

Hexadecimal format

e or E

Exponential notation

f or F

Floating-point decimal

g or G

General format

c

Single Character

r

String format(using repr())

s

String Format(using str()))

%

Percentage


Next Article
Different Input and Output Techniques in Python3

A

ABHISHEK TIWARI 13
Improve
Article Tags :
  • Python
Practice Tags :
  • python

Similar Reads

    Python Tutorial | Learn Python Programming Language
    Python Tutorial – Python is one of the most popular programming languages. It’s simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
    10 min read
    Input and Output in Python
    Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
    8 min read

    Python basic I/O Techniques

    Taking input in Python
    Developers often have a need to interact with users, either to get data or to provide some sort of result. Most programs today use a dialog box as a way of asking the user to provide some type of input. While Python provides us with two inbuilt functions to read the input from the keyboard. input ()
    3 min read
    Python input() Function
    Python input() function is used to take user input. By default, it returns the user input in form of a string.input() Function Syntax: input(prompt)prompt [optional]: any string value to display as input messageEx: input("What is your name? ")Returns: Return a string value as input by the user.By de
    4 min read
    Taking input from console in Python
    What is Console in Python? Console (also called Shell) is basically a command line interpreter that takes input from the user i.e one command at a time and interprets it. If it is error free then it runs the command and gives required output otherwise shows the error message. A Python Console looks
    2 min read
    Python - Print Output using print() function
    Python print() function prints the message to the screen or any other standard output device. In this article, we will cover about print() function in Python as well as it's various operations.Python# print() function example print("GeeksforGeeks") a = [1, 2, 'gfg'] print(a) print() Function Syntax
    4 min read
    Python - Output Formatting
    In Python, output formatting refers to the way data is presented when printed or logged. Proper formatting makes information more understandable and actionable. Python provides several ways to format strings effectively, ranging from old-style formatting to the newer f-string approach.Formatting Out
    5 min read

    Python3 I/O

    Different Input and Output Techniques in Python3
    An article describing basic Input and output techniques that we use while coding in python. Input Techniques 1. Taking input using input() function -> this function by default takes string as input.  Example: Python3 #For string str = input() # For integers n = int(input()) # For floating or deci
    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