operations with empty strings | zfill () function

NumPy | Python Methods and Functions | String Variables | zfill

numpy.core.defchararray.zfill (arr, width) — this is another function for doing string operations in numpy. For each element in the array, it returns a numeric string filled with zeros on the left. The number of padded zeros on the left occurs 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:

# Program Python explaining
# numpy.char.zfill () method

 
# numpy import

import numpy as geek

 
# input array

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

print ( "Input array: " , in_arr) 

  
# set the width of each line to 8

width = 8

 
# output array

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

print ( "Output array: " , out_arr) 

 

Exit:

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

Code # 2:

# Python program explaining
# numpy.char.zfill () method

  
# numpy import

import numpy as geek

 
# input array

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

  print ( "Input array:" , in_arr)

 
# set the width of each line to 5

width = 5

 
# output array

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

print ( "Output array:" , out_arr) 

Exit:

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




operations with empty strings | zfill () function: StackOverflow Questions

Answer #1

Strings:

>>> n = "4"
>>> print(n.zfill(3))
004

And for numbers:

>>> n = 4
>>> print(f"{n:03}") # Preferred method, python >= 3.6
004
>>> print("%03d" % n)
004
>>> print(format(n, "03")) # python >= 2.6
004
>>> print("{0:03d}".format(n))  # python >= 2.6 + python 3
004
>>> print("{foo:03d}".format(foo=n))  # python >= 2.6 + python 3
004
>>> print("{:03d}".format(n))  # python >= 2.7 + python3
004

String formatting documentation.

Answer #2

You can use str.zfill:

print(str(1).zfill(2))
print(str(10).zfill(2))
print(str(100).zfill(2))

prints:

01
10
100

Answer #3

You can use the zfill() method to pad a string with zeros:

In [3]: str(1).zfill(2)
Out[3]: "01"

Answer #4

Besides zfill, you can use general string formatting:

print(f"{number:05d}") # (since Python 3.6), or
print("{:05d}".format(number)) # or
print("{0:05d}".format(number)) # or (explicit 0th positional arg. selection)
print("{n:05d}".format(n=number)) # or (explicit `n` keyword arg. selection)
print(format(number, "05d"))

Documentation for string formatting and f-strings.

Get Solution for free from DataCamp guru