Python3 : How to pad zeroes or any character to a string?

This article discusses about two ways to pad either to the left or right of a string with zeros, spaces or any character.

Left padding :

Left padding means adding characters like zeroes or spaces or any character to the left side of a string.

Example: Suppose a target string is “5” hence left padding it by three zeroes will give us a string like “0005″.

Syntax: string.zfill(width)

Pads a target string with zeroes on the left until it reaches the specified width.

Original_String = "5"
print("Original String : " + Original_String) 

Modified_String = Original_String.zfill(6)
print("Modified String : " + Modified_String)

The output should look like this

Original String : 5 
Modified String : 000005

Syntax: string.rjust(length, character)

Makes the given string right justified by padding filler char to the left of string to make it’s length equal to the specified length as parameter.

Original_String = "5" 
Modified_String = Original_String.rjust(20,"0") 

print("Original String : " + Original_String) 
print("Modified String : " + Modified_String)

The output should look like this.

Original String : 5  

Modified String : 00000000000000000005

Right padding

Right padding means adding characters like zeroes or spaces or any character to the right side of a string.

Example: Suppose a target string is “5” hence right padding it by three zeroes will give us a string like “5000“.

Syntax: string.ljust(length, character)

Original_String = "5" 
Modified_String = Original_String.ljust(20,"0") 

print("Original String : " + Original_String) 
print("Modified String : " + Modified_String)

The output should look like this.

Original String : 5  

Modified String : 50000000000000000000

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *