NumPy strings.zfill()
The numpy.strings.zfill()
function left-fills a numeric string with zeros up to the specified width. If the string contains a sign (+/-), the padding is inserted after the sign.
Syntax
</>
Copy
numpy.strings.zfill(a, width)
Parameters
Parameter | Type | Description |
---|---|---|
a | array-like (StringDType, bytes_, or str_) | Input array containing string values to be zero-filled. |
width | array_like (integer dtype) | Desired total width of the string after zero-padding. |
Return Value
Returns an ndarray containing the input strings left-filled with zeros up to the specified width.
Examples
1. Zero-Filling a Single String
Here, we left-fill the string 'apple'
with zeros to make its length 10.
</>
Copy
import numpy as np
# Define a single string
fruit = np.array('apple', dtype='str')
# Apply zfill to make the total length 10
result = np.strings.zfill(fruit, 10)
# Print the result
print("Zero-filled string:", result)
Output:
Zero-filled string: 00000apple

2. Zero-Filling an Array of Strings
We apply zfill
to multiple fruit names, ensuring each has a length of 8.
</>
Copy
import numpy as np
# Define an array of fruit names
fruits = np.array(['apple', 'banana', 'cherry'], dtype='str')
# Apply zfill to make all strings of length 8
result = np.strings.zfill(fruits, 8)
# Print the results
print("Zero-filled strings:", result)
Output:
Zero-filled strings: ['000apple' '00banana' '00cherry']

3. Zero-Filling Strings with Numeric Values
We use zfill
to pad numeric strings while preserving sign placement.
</>
Copy
import numpy as np
# Define an array with numeric strings (including a signed number)
numbers = np.array(['42', '-5', '+78'], dtype='str')
# Apply zfill to ensure a width of 5 characters
result = np.strings.zfill(numbers, 5)
# Print the results
print("Zero-filled numeric strings:", result)
Output:
Zero-filled numeric strings: ['00042' '-0005' '+0078']

The numeric values are padded with zeros, and the signs are maintained correctly.