Add trailing Zeros to a Python string

PythonServer Side ProgrammingProgramming

As part of data processing activity we sometimes need to append one string with another. In this article we will see how to append dynamic number of zeros to a given string. This can be done by using various string functions as shown in the programs below.

Using ljust and len

Python string method ljust() returns the string left justified in a string of length width. Padding is done using the specified fillchar (default is a space). The len() returns the length of the string. We add trailing zeros to the string by manipulating the length of the given string and the ljust function.

Example

#Add trailing Zeros to a Python string
# initializing string
str = 'Jan-'
print("The given input : " + str(str))
# No. of zeros required
n = 3
# using ljust() adding trailing zero
output = str.ljust(n + len(str), '0')
print("adding trailing zeros to the string is : " + str(output))

Output

Running the above code gives us the following result −

The given input : Jan-
adding trailing zeros to the string is : Jan-000

Using format Function

The format() method formats the specified value and insert them inside the string's placeholder. The placeholder is defined using curly brackets: {}. In the below example we take a string of length 7 and use format method to add two trailing zeros.

Example

str= 'Spring:'
print("\nThe given input : " + str(str))
# using format()adding trailing zero n for number of elememts, '0' for Zero, and '<' for trailing
z = '{:<09}'
output = z.format(str)
print("adding trailing zeros to the string is : " + str(output))

Output

Running the above code gives us the following result −

The given input : Spring:
adding trailing zeros to the string is : Spring:00
raja
Published on 14-Feb-2020 11:43:26
Advertisements