numpy string operations | zfill() function (original) (raw)

Last Updated : 28 Jan, 2019

numpy.core.defchararray.zfill(arr, width) is another function for doing string operations in numpy. For each element in the array it returns the numeric string left-filled with zeros.The number of left filled zeros happen according to the width.

Parameters:
arr : array_like of str or unicode.Input array.
width : [int] The final width of the string after filling zeros.

Returns : [ndarray] Output array of str or unicode, depending on input type.

Code #1 :

import numpy as geek

in_arr = geek.array([ 'Geeks' , 'for' , 'Geeks' ])

print ( "Input array : " , in_arr)

width = 8

out_arr = geek.char.zfill(in_arr, width)

print ( "Output array: " , out_arr)

Output:

Input array : ['Geeks' 'for' 'Geeks'] Output array: ['000Geeks' '00000for' '000Geeks']

Code #2 :

import numpy as geek

in_arr = geek.array([ '1' , '11' , '111' ])

print ( "Input array : " , in_arr)

width = 5

out_arr = geek.char.zfill(in_arr, width)

print ( "Output array: " , out_arr)

Output:

Input array : ['1' '11' '111'] Output array: ['00001' '00011' '00111']

Similar Reads