

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Add trailing Zeros to a Python string
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
- Related Questions & Answers
- Add leading Zeros to Python string
- Add leading Zeros to Python Program string
- Remove Trailing Zeros from string in C++
- Finding trailing zeros of a factorial JavaScript
- Add leading zeros to a MySQL column?
- Count trailing zeros in factorial of a number in C++
- C Program to count trailing and leading zeros in a binary number
- How to get a string leftpadded with zeros in Python?
- Java Program to add leading zeros to a number
- Program to find trailing zeros in factorial of n in C++?\n
- How to remove all trailing whitespace of string in Python?
- Remove trailing zeros in decimal value with changing length in MySQL?
- Count number of trailing zeros in product of array in C++
- How to remove all trailing and leading whitespace in a string in Python?
- How to add zeros before numbers in R?