What is the numpy.char.zfill() function from NumPy in Python?

Overview

Python’s char.zfill() function is used to return the numeric string left-filled with zeros.

Syntax

char.zfill(a, width)

Parameter

The char.zfill() function takes the following parameter values:

  • a: The input array of strings or Unicode.
  • width: The width of the string to left, fill elements in the input array. In other words, it is the final width of the string after filling with zeros.

Return value

The char.zfill() function returns an array of string or Unicode, depending on the input type.

Example

Let’s look at the code below:

import numpy as np
# creating an array
myarray = np.array(["That", "There", "These", "They"])
# implementing the char.zfill() function using a widht of 10
print(np.char.zfill(myarray, 10))

Explanation

  • Line 1: We import the numpy module.
  • Line 4: We create an array of string myarray using the array() function.
  • Line 7: We implement the char.zfill() function on the array using a width value of 10.

Free Resources