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:
How to Create Array of zeros using Numpy in Python
Next article icon

How to Add leading Zeros to a Number in Python

Last Updated : 24 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will learn how to pad or add leading zeroes to the output in Python.

Example:

Input: 11 Output: 000011 Explanation: Added four zeros before 11(eleven).

Display a Number With Leading Zeros in Python

Add leading Zeros to numbers using format()

For more effective handling of sophisticated string formatting, Python has included the format() method. A formatter inserts one or more replacement fields and placeholders into a string by using the str.format function and a pair of curly braces ().

Python3
print("{:03d}".format(1))  print("{:05d}".format(10)) 

Output
001 00010

Add leading Zeros to the number using f-string

Prefix the string with the letter "f" to get an f-string. The string itself can be prepared similarly to how str.format would be used (). F-strings offer a clear and practical method for formatting python expressions inside of string literals.

Python3
num1 = 16  print(f" {num1 : 03d} ") print(f" {num1 : 07d} ") 

Output
  16    000016 

Add zeros using  rjust() method :

One approach that is not mentioned in the article is using the rjust() method of the built-in str class to add leading zeros to a number. The rjust() method returns a right-justified string, with optional padding, based on a specified width.

Here is an example of how you could use the rjust() method to add leading zeros to a number:

Python3
num = 11 padded_num = str(num).rjust(6, '0') print(padded_num)  # Output: 000011 

Output
000011

Using the rjust() method can be a simple and concise way to add leading zeros to a number, especially if you only need to pad the number with a fixed number of zeros. It is also useful if you need to pad a number that is stored as a string, as it works directly on strings.

Note that the rjust() method returns a new string, so you will need to store the padded number in a separate variable if you want to keep it. 

Add zeros using  zfill() method :

The zfill() method adds zeros (0) at the beginning of the string, until it reaches the specified length. If the value of the len parameter is less than the length of the string, no filling is done.

Below is the implementation:

Python3
num = '42' ans = num.zfill(8) print(ans)  

Output
00000042

Method :Using the % operator with the 0 flag:

Python3
num = 42 res = "%06d" % num print(res) 

Output
000042

Add zeros using join() method :

  • Converting the number to a string using the str()
  • Finding the length of the string using the len().
  • The join() method is commonly concatenate a sequence of strings with a specified separator
  • Concatenating the list of zeros and the original string using the + operator
  • Assigning the result to padded_num
Python3
num = 11 padded_num = "".join(["0"] * (6 - len(str(num)))) + str(num) print(padded_num)  # Output: 000011 

Output
000011

Time complexity: O(n), where n is the number of zeros to be added.

Space Complexity: O(n), where n is the number of zeros to be added.


Next Article
How to Create Array of zeros using Numpy in Python

S

shinderajashree80
Improve
Article Tags :
  • Python
Practice Tags :
  • python

Similar Reads

  • How to Round Numbers in Python?
    Rounding a number simplifies it while keeping its value as close as possible to the original. Python provides various methods to round numbers, depending on how we want to handle the precision or rounding behavior. In this article, we'll cover the most commonly used techniques for rounding numbers i
    4 min read
  • Add padding to a string in Python
    Padding a string involves adding extra characters such as spaces or specific symbols to adjust its length or align it in a visually appealing way. Let’s dive into the most efficient methods to add padding to a string in Python. Using Python f-stringsF-strings allow us to specify padding directly wit
    2 min read
  • How to add Elements to a List in Python
    In Python, lists are dynamic which means that they allow further adding elements unlike many other languages. In this article, we are going to explore different methods to add elements in a list. For example, let's add an element in the list using append() method: [GFGTABS] Python a = [1, 2, 3] a.ap
    2 min read
  • Python | pandas int to string with leading zeros
    In Python, When it comes to data manipulation and data analysis, Panda is a powerful library that provides capabilities to easily encounter scenarios where the conversion of integer to string with leading zeros is needed. In this article, we will discuss How we can convert pandas int to string with
    4 min read
  • How to Create Array of zeros using Numpy in Python
    numpy.zeros() function is the primary method for creating an array of zeros in NumPy. It requires the shape of the array as an argument, which can be a single integer for a one-dimensional array or a tuple for multi-dimensional arrays. This method is significant because it provides a fast and memory
    4 min read
  • Python | C++ | Remove leading zeros from an IP address
    Given an IP address, remove leading zeros from the IP address. Examples: Input : 100.020.003.400 Output : 100.20.3.400 Input :001.200.001.004 Output : 1.200.1.4Recommended PracticeRemove leading zeros from an IP addressTry It! The approach is to split the given string by “.” and then convert it to a
    4 min read
  • Words to Numbers Converter Tool in Python
    In this tutorial, we will guide you through the process of building a Word-to Numbers converter using Python. To enhance the user experience, we will employ the Tkinter library to create a simple and intuitive Graphical User Interface (GUI). This tool allows users to effortlessly convert words into
    2 min read
  • How to Change Values in a String in Python
    The task of changing values in a string in Python involves modifying specific parts of the string based on certain conditions. Since strings in Python are immutable, any modification requires creating a new string with the desired changes. For example, if we have a string like "Hello, World!", we mi
    2 min read
  • How To Convert Unicode To Integers In Python
    Unicode is a standardized character encoding that assigns a unique number to each character in most of the world's writing systems. In Python, working with Unicode is common, and you may encounter situations where you need to convert Unicode characters to integers. This article will explore five dif
    2 min read
  • How to convert string to integer in Python?
    In Python, a string can be converted into an integer using the following methods : Method 1: Using built-in int() function: If your string contains a decimal integer and you wish to convert it into an int, in that case, pass your string to int() function and it will convert your string into an equiv
    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