NumPy String: numpy.char.zfill() function
numpy.char.zfill() function
The numpy.char.zfill() function is used to pad a string with zeros on the left side.
This function is useful for formatting strings that need to have a fixed length, such as numbers with leading zeros.
Syntax:
numpy.char.zfill(a, width)
Parameters:
Name | Description | Required / Optional |
---|---|---|
a: array_like, {str, unicode} | Input array. | Required |
width: int | Width of string to left-fill elements in a. | Required |
Return value:
Output array of str or unicode, depending on input type.
Example: Filling zeros to left of string using numpy.char.zfill()
>>> import numpy as np
>>> a = np.char.zfill('w3resource', 20)
>>> a
array('0000000000w3resource', dtype='<U20')
In the above code, the string 'w3resource' is filled with zeros to make it of length 20. The resulting output is an array with dtype <U20. This means the array has Unicode strings of length 20.
Pictorial Presentation:
Example: Filling zeros to the left of a string using numpy.char.zfill()
>>> import numpy as np
>>> b = np.char.zfill('hello', 20)
>>> b
array('000000000000000hello', dtype='<U20')
In the above code numpy.char.zfill() function is applied to the string 'hello' with a width of 20. The resulting array contains the string 'hello' with 15 leading zeros to make the length of the string 20 characters.
Pictorial Presentation:
Python - NumPy Code Editor:
Previous:
upper()
Next:
String information count()
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/numpy/string-operations/zfill.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics