English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python basic tutorial

Python flow control

Funções do Python

Tipos de Dados do Python

Python file operation

Python objects and classes

Python date and time

Advanced knowledge of Python

Python reference manual

Python string zfill() usage and example

Python string methods

The zfill() method returns a copy of the string, which fills '0' characters on the left.

The syntax of zfill() in Python is:

str.zfill(width)

zfill() parameter

zfill() uses a single character width.

The width specifies the length of the string returned from zfill(), and fills '0' on the left.

zfill() return value

zfill() returns a copy of the string, which is filled with '0' on the left. The length of the returned string depends on the provided width.

  • Assuming the initial length of the string is10,and the width it specifies will be15。In this case, zfill() returns a copy of the string, which is filled with five '0' digits on the left.

  • Assuming the initial length of the string is10,and the width it specifies will be8.In this case, zfill() will not fill '0' on the left and return a copy of the original string. In this case, the length of the returned string will be10.

Example1:How does zfill() work in Python?

text = "program is fun"
print(text.zfill(15))
print(text.zfill(20))
print(text.zfill(10))

When running the program, the output is:

0program is fun
000000program is fun
program is fun

If the string starts with a symbol prefix ('+',-The character prefix at the beginning, then fill '0' digits after the first character prefix.

Example2:How to use zfill() with Sign Prefix?

number = "-290"
print(number.zfill(8))
number = "+290"
print(number.zfill(8))
text = "--random+text"
print(text.zfill(20))

When running the program, the output is:

-0000290
+0000290
-0000000-random+text

Python string methods