Home > Backend Development > Python Tutorial > How to Pad Strings and Numbers with Zeros in Python?

How to Pad Strings and Numbers with Zeros in Python?

Mary-Kate Olsen
Release: 2024-12-19 17:48:10
Original
834 people have browsed it

How to Pad Strings and Numbers with Zeros in Python?

Padding Strings with Zeros

In Python, strings and numbers can be padded with zeros to a specific length. Here's how to achieve this:

Padding Strings

To pad a string with zeros, use the zfill() method. For example:

n = '4'
print(n.zfill(3))  # Output: 004
Copy after login

This will pad the string with zeros until it reaches the specified length.

Padding Numbers

Numbers can be padded with zeros using various methods:

  • Formatted String Literals (f-strings):
n = 4
print(f'{n:03}')  # Output: 004
Copy after login
  • Formatted String Operator:
n = 4
print('%03d' % n)  # Output: 004
Copy after login
  • String Format Method:
n = 4
print(format(n, '03'))  # Output: 004
Copy after login
  • Named Formatted Strings:
n = 4
print('{0:03d}'.format(n))  # Output: 004
Copy after login
  • Keyword Formatted Strings:
n = 4
print('{foo:03d}'.format(foo=n))  # Output: 004
Copy after login
  • String Interpolation:
n = 4
print('{:03d}'.format(n))  # Output: 004
Copy after login

For more information on string formatting, refer to the official Python documentation.

The above is the detailed content of How to Pad Strings and Numbers with Zeros in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template