Python How to Pad Zeros to a String?

Rate this post

Have you ever had a string and wanted to make it a certain length by adding zeros to it? You could type it out. But we’re programmers, we hate typing! Surely there must be a way to code this? 

Python How to Pad Zeros to a String?

To pad zeros to a string, use the str.zfill() method. It takes one argument: the final length of the string you want and pads the string with zeros to the left.

>>> a = '12345'
>>> b = a.zfill(10)
# b is 10 characters long
>>> len(b)
>>> b

If you enter a value less than the length of the string, it returns the string unmodified.

>>> a = '12345'
>>> b = a.zfill(3)
# b is the same as a, as 3 < len(a)
>>> b

Let’s dive into a more detailed overview of string padding and the different options you have.


We highly recommend watching the video for this article. The ideas can be hard to understand at first. Having Adam to guide you makes it much easier.

Python How to Pad Zeros to a String Video

Python String Padding Methods

Python has several built-in string methods to pad strings. You are not limited to zeros but can pad with any character. 

Their names are very easy to remember:

  • ljust — return string left justified 
  • rjust — return string right justified
  • center — return string centered

They all have the same syntax

str.ljust(width, fillchar=' ')
str.rjust(width, fillchar=' '), fillchar=' ')
  • The first argument is width. It is the length of the string you want to return. If you enter a width smaller than len(str), Python returns str unmodified. 
  • The second argument, fillchar, is optional. Use is to specify the character you want to use to pad your string. By default, it is a space but you can use anything. If you pass a string longer than one character, Python raises a TypeError.

Do you want to develop the skills of a well-rounded Python professional—while getting paid in the process? Become a Python freelancer and order your book Leaving the Rat Race with Python on Amazon (Kindle/Print)!

Leaving the Rat Race with Python Book

Let’s look at some examples for each method.

Examples str.ljust()

>>> a = 'hello'

# Width 10
>>> a.ljust(10)
'hello     '

# Width 40
>>> a.ljust(40)
'hello                                   '

# Width 10 padded with 0
>>> a.ljust(10, '0')

# Width 40 padded with -
>>> a.ljust(40, '-')

# TypeError as fill character has len > 1
>>> a.ljust(10, '12')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: The fill character must be exactly one character long

Examples str.rjust()

>>> a = 'hello'

# Width 10
>>> a.rjust(10)
'     hello'

# Width 40
>>> a.rjust(40)
'                                   hello'

# Width 10 padded with 0
>>> a.rjust(10, '0')

# Width 40 padded with -
>>> a.rjust(40, '-')

# TypeError as fill character has len > 1
>>> a.rjust(10, '12')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: The fill character must be exactly one character long


Note: if the middle of your string is not exactly the middle of width, Python will slightly left justify it. This is the case in all examples below that use an even width.

>>> a = 'hello'

# Width 10
'  hello   '

# Width 40
'                 hello     '

# Width 10 padded with 0
>>>, '0')

# Width 40 padded with -
>>>, '-')

# TypeError as fill character has len > 1
>>>, '12')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: The fill character must be exactly one character long

# Width 11 - perfectly centered, 3 x 0 on either side
>>>, '0')

Python String Padding Format Methods

If you are using complex print() statements, you will want to use f-strings or the format method at some point. Thankfully, we can easily pad strings this way too.

F-strings were introduced in Python 3.6. They are the de-facto standard for string formatting in Python. But we will include the format() method for completeness. 

Check out the official Python docs for a detailed overview. Warning, they are tricky to understand. So don’t be put off if it takes you a while to understand them.

Python String Padding Using F-Strings

F-strings are incredibly powerful. We will only cover how to pad strings but check out this article for a detailed overview. 

You denote f-strings by placing an f or F in front of a string. Their key feature is called a replacement field. It is denoted by curly braces {}. Inside the braces, you can put variables, expressions or even functions. This is incredibly helpful as it gives your strings lots of flexibility. 

For this article, we will focus on calling variables within strings, for example:

>>> name = 'John Cleese'
>>> print(f'I am called {name}')
I am called John Cleese

You can modify the string inside the replacement field. You can pad, align and change its length. This is called format specification in Python, or format_spec for short. In an f-string, you specify this using a colon :. Everything after the colon is a formatting option. It will not be printed to the screen. Let’s look at the syntax to pad, align and change the length of a string.

We type the following in this order, after a colon :

  • fill: character to use for padding 
  • align: use <, > or ^ to have left, right or center alignment
  • width: integer value stating total length of string

Example: So if we want to pad our string with zeros, i.e. fill 0, right align and have width 10, we would use

  • fill: 0
  • right align: >
  • width: 10

This code shows this exact example in action:

>>> a = 'hello'
>>> print(f'{a:0>10}')

Let’s see what happens when we change each of these options. First, we’ll choose a different fill character.

# Use hyphen fill character
>>> print(f'{a:->10}')

# If we specify no fill character, space is used
>>> print(f'{a:>10}')

# Exclamation mark fill character
>>> print(f'{a:!>10}')

We’ll now change the alignment. The sign points in the direction of alignment i.e. < is left align and upwards ^ is center align.

# Use hyphen fill character, left align
>>> print(f'{a:-<10}')

# If we specify no fill character, space is used, left align
>>> print(f'{a:<10}')

# Exclamation mark fill character, center align
>>> print(f'{a:!^10}')

Lastly, we will change the string length.

# Hyphen fill character, right align, length 40
>>> print(f'{a:->40}')

# If we specify no fill character, space is used, right align, length 25
>>> print(f'{a:>25}')

# Exclamation mark fill character, center align, length 33
>>> print(f'{a:!^33}')

To pad multiple strings, use multiple replacement fields (curly braces {}).

>>> a = 'hello'
>>> b = 'world!'

# a - pad with underscore, center align, length 11
# b - pad with 0, right align, length 10
>>> print(f'{a:_^11} some extra text {b:0>10}')
___hello___ some extra text 0000world!

Padding Using .format()

Padding with format() is similar to f-strings. 

a = 'hello'

# These are the same
# a - pad with hyphen, right align, length 40

# Output

You can pass strings directly to format if you’d like:

# These are the same
# a - pad with hyphen, right align, length 40

# Output

The format_spec syntax (everything after the colon) is the same when using f-strings or format. The difference is that you pass a to format() rather than placing it within the replacement field {}. Or you can type the string directly into format()

Padding multiple strings can get more complex when using format(). Let’s say you have two replacement fields and pass two variables to format(a, b). Then a will go to the first and b to the second. 

a = 'hello'
b = 'world!'

# These are the same
# F-string
print(f'{a:_^11} some extra text {b:0>10}')

# Format
# a first, then b
print('{:_^11} some extra text {:0>10}'.format(a, b))

# Output
___hello___ some extra text 0000world!

To be more explicit, you can refer to the arguments of format with indexes starting from 0. This lets you call variables in whatever order you want.

# These are the same
print('{:_^11} some extra text {:0>10}'.format(a, b))

# a is index 0, b is index 1
print('{0:_^11} some extra text {1:0>10}'.format(a, b))
# ___hello___ some extra text 0000world!

# Call b from firt replacement field and a from the second.
print('{1:_^11} some extra text {0:0>10}'.format(a, b))
# __world!___ some extra text 00000hello

Finally, you do not need to specify variables when you use format. You can pass the strings to directly instead.

# These are the same
print('{:_^11} some extra text {:0>10}'.format(a, b))
print('{:_^11} some extra text {:0>10}'.format('hello', 'world!'))
# ___hello___ some extra text 0000world!

Which Should You Choose – Format or F-Strings?

Python introduced f-strings in PEP 498. One of the reasons for this is because format() syntax can be verbose, slow and hard to read. F-strings solve all these problems. They are simple, very fast and easy to read. So, you should always use them instead of format(). Yet, it is useful to know format() syntax in case you read it in someone else’s code. 

Python Int to String with Leading Zeros

To convert an integer i to a string with leading zeros so that it consists of 5 characters, use the format string f'{i:05d}'. The d flag in this expression defines that the result is a decimal value. The str(i).zfill(5) accomplishes the same string conversion of an integer with leading zeros.

Challenge: Given an integer number. How to convert it to a string by adding leading zeros so that the string has a fixed number of positions.

Example: For integer 42, you want to fill it up with leading zeros to the following string with 5 characters: '00042'.

In all methods, we assume that the integer has less than 5 characters.

Method 1: Format String

The first method uses the format string feature in Python 3+. They’re also called replacement fields.

# Integer value to be converted
i = 42

# Method 1: Format String
s1 = f'{i:05d}'
# 00042

The code f'{i:05d}' places the integer i into the newly created string. However, it tells the format language to fill the string to 5 characters with leading '0's using the decimal system. This is the most Pythonic way to accomplish this challenge.

Method 2: zfill()

Another readable and Pythonic way to fill the string with leading 0s is the string.zfill() method.

# Method 2: zfill()
s2 = str(i).zfill(5)
# 00042

The method takes one argument and that is the number of positions of the resulting string. Per default, it fills with 0s.

Related Article: Python Int to String with Leading Zeros


In this article, you learned many different ways you can pad zeros (and any other character) to strings.

If you just want to pad zeros on the left of the string, there is nothing better than the zfill() method. It was designed to solve this problem.

To pad different characters, use ljust(), rjust() and center(). Or you can use f-strings or the format() method. 

The built-in methods are much easier to learn, read and implement. But it’s important you know them all. You’ll see everything out in the wild!

Where To Go From Here

Do you want to earn more money? Are you in a dead-end 9-5 job? Do you dream of breaking free and coding full-time but aren’t sure how to get started? 

Becoming a full-time coder is scary. There is so much coding info out there that it’s overwhelming. 

Most tutorials teach you Python and tell you to get a full-time job. 

That’s ok but why would you want another office job?

Don’t you crave freedom? Don’t you want to travel the world? Don’t you want to spend more time with your friends and family?

There are hardly any tutorials that teach you Python and how to be your own boss. And there are none that teach you how to make six figures a year.

Until now. 

I am a full-time Python freelancer. I work 4 hours a day from anywhere in the world. I set my own schedule and hourly rate. My calendar is booked out months in advance and I have a constant flow of new clients. 

Sounds too good to be true, right?

Not at all. I want to show you the exact steps I used to get here. I want to give you a life of freedom. I want you to be a six-figure coder.

Click the link below to watch my pure-value webinar. I’ll show you the exact steps to take you from where you are to a full-time Python freelancer. These are proven, no-BS methods that get you results fast.

It doesn’t matter if you’re a Python novice or Python pro. If you are not making six figures/year with Python right now, you will learn something from this webinar.

This webinar won’t be online forever. Click the link below before the seats fill up and learn how to become a Python freelancer.


The official Python docs for string formatting are notoriously difficult to understand. Thankfully, there are a lot of great resources online. Check out our favourites below.