zfill(): add zeros to a string in Python

Use the zfill() to insert zeros 0 at the beginning of a string.

The amount of zeros is given by the number passed as argument minus the number of chars in the string.

The word ‘beach’ has 5 characters, which gives us 27 spaces to fill with zeros to make it 32 total as specified in the variable size_string

word = 'beach'
size_string = 32

word_zeros = word.zfill(size_string)

print(word)
#beach

print(word_zeros)
#000000000000000000000000000beach

The original word variable remains unchanged, thus we need to assign the return of the method to a new variable, word_zeros in this case.

Also notice that if the argument is less than the number of chars in the string, nothing changes.

In the example below, ‘beach’ has 5 chars and we want to add zeros until it reaches the size_string of 4, which means there is nothing to be done.

word = 'beach'
size_string = 4

word_zeros = word.zfill(size_string)

print(word)
#beach

print(word_zeros)
#'beach'