• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

Python Padding | How to Pad Zeros to Number or String?

Aniruddha Chaudhari/99969/6
CodePython

Many times to represent the data or display it on the output console, we need to pad a number with extra zeros to make it looks consistent.

In this post, I a going to share the simplest two methods for Python padding.

Before jumping into the code, let’s see…

If you have the serial number from 0 to 999. It looks something like this…

0
1
2
.
.
8
9
.
.
25
26
17
.
.
997
998
999

The number series does not look fancy as the length of the number in the series varies. If we pad the number to make it have the same length (says 3), it looks like this…

If we pad the number to make it have the same length (says 3), it looks like this…

000
001
002
.
.
008
009
.
.
025
026
017
.
.
997
998
999

From the above two number series list, which one does look good?

I am sure, it’s Second!

So let’s see how to pad integer number and string in Python.

Python Padding:

There are multiple methods of doing this. Let’s check some of the simple Python tricks…

Method 1: Using zfill()

strNum = '7'
print strNum.zfill(3)

The zfill is a function associated with the string object. 3 is the expected length of the string after padding.

Method 2: Using rjust()

strNum = '7'
strNum.rjust(3, '0')

The rjust() is string inbuilt function in Python. Pass the expected length of the string after padding and character to be used for padding as two parameters of the function.

With this function, you can use any character for padding.

Output:

Both the method will give the same output as…

007

“1” gives out as a string of “001”

“2” gives “002”, “99” gives “099”, “100” gives “100”, “999” gives “999”

Exception: If the length of the given string is greater than the padding length, it returns the same string.

Above code returns “7000” for “7000” even if you pass 3 as expected length after padding.

In Python, you can not pad the integer number. You have to convert the number into the string. And then pad it.

Conversion of the integer into the string is very easy.

num = 7
strNum = str(num)

Now you can make the consistent length for all the numbers in series.

This function will be more helpful if you have a function that manipulates the same length of the input string.

Other Python Tricks:

  • Swap Two Variables without using Third Variable [in just one line of code]
  • Get all the Permutations of String
  • Reverse String in Python [using Extended Slice Syntax ]

This is all about Python padding. There are so many other methods of doing this. To make it simple to use in your code, I have listed the simplest two methods.

If you think as there are other simplest ways of solving this problem, comment below. I am sure it will be helpful other Python Programmers.

Python Interview Questions eBook

Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Comments

  • Reply
    Kęstutis
    November 8, 2017 at 6:13 am

    Hi Aniruddha,

    padding is a cute thing, thanks! Any ideas on how to do the reverse thing as easy as it is with padding?
    I mean geeting back integers from padded strings.

    • Reply
      Aniruddha Chaudhari
      November 8, 2017 at 4:37 pm

      Hey Kęstutis, Glad to see you here!

      There is no padding for integer values in Python. So, when you convert the number from integer to string, there will be no padded zeros.

      Use int() function to convert the string into the integer.

  • Reply
    Charlie Munro
    November 9, 2017 at 9:33 pm

    Yes, zfill(n) is quick and easy. If you want flexibility make sure you know about str.format(). For example:

    print('{0:03d}'.format(n))

    Lot’s of options there for int and float. Used it in a problem on HackerRank yesterday.

    • Reply
      Aniruddha Chaudhari
      November 10, 2017 at 3:00 am

      Yeah, you Right!

      There are so many options for doing this in Python. The one you have mentioned is even good to go for those having a good understanding of str.format().

  • Reply
    Harry
    February 23, 2020 at 12:56 pm

    I am trying to increase the security of an algorithm by introducing padding using ljust(), the problem is on decryption, I need to get the stream without padding how do I achieve this?

    • Reply
      Aniruddha Chaudhari
      February 23, 2020 at 1:37 pm

      To remove padded elements, you can use the string method strip().

Leave a Reply Cancel reply

Basic Python Tutorial

  1. Python- Tutorial Overview
  2. Python- Applications
  3. Python- Setup on Linux
  4. Python- Setup on Windows
  5. Python- Basic Syntax
  6. Python- Variable Declaration
  7. Python- Numeric Data Types
  8. Python- NoneType
  9. Python- if-else/elif
  10. Python- for/while else
  11. Python- User Input
  12. Python- Multiline User Input
  13. Python- String Formatting
  14. Python- Find Substring in String
  15. Python- Bitwise Operators
  16. Python- Range Function
  17. Python- List
  18. Python- List Vs Tuple
  19. Python- Compare Two Lists
  20. Python- Sorting List
  21. Python- Delete Element from List
  22. Python- Dictionary
  23. Python- ‘is’ vs ‘==’
  24. Python- Mutable vs Immutable
  25. Python- Generator & Yield
  26. Python- Fibonacci Generator
  27. Python- Assert Statement
  28. Python- Exception Handling 
  29. Python- RegEx
  30. Python- Lambda Function
  31. Python- Installing Modules
  32. Python- Important Modules
  33. Python- Find all Installed Modules
  34. PyCharm- IDE setup
  35. Python- File Handling
  36. Python- Monkey Patching
  37. Python- Decorators
  38. Python- Instance vs Static vs Class Method
  39. Python- Name Mangling
  40. Python- Working with GUI
  41. Python- Read Data from Web URL
  42. Python- Memory Management
  43. Python- Virtual Environment
  44. Python- Calling C Function

Python Exercise

  1. Python- Tricky Questions
  2. Python- Interview Questions (60+)
  3. Python- Project Ideas (45+)
  4. Python- MCQ Test Online
  5. Python- Coding Questions (50+)
  6. Python- Competitive Coding Questions (20+)

Python String

  1. Reverse the String
  2. Permutations of String
  3. Padding Zeros to String/Number

Python List

  1. Randomly Select Item from List
  2. Find Unique Elements from List
  3. Are all Elements in List Same?

Python Dictionary

  1. Set Default Value in Dictionary
  2. Remove all 0 from a dictionary

File Handling

  1. Python- Read CSV File into List
  2. Check if the File Exist in Python
  3. Find Longest Line from File

Compilation & Byte Code

  1. Multiple Py Versions on System
  2. Convert .py file .pyc file
  3. Disassemble Python Bytecode

Algorithms

  1. Sorting- Selection Sort
  2. Sorting- Quick Sort

Other Python Articles

  1. Clear Py Interpreter Console
  2. Can I build Mobile App in Python?
  3. Extract all the Emails from File
  4. Python Shell Scripting

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard