A Tip A Day – Python Tips #12: Using zfill() for ‘0’ padding

Lets learn a Python Tip which can help you in string manipulation. It is very useful various data processings.

zfill() function:

zfill() function is type of padding function.

This function fills only with ‘0’. Takes the resultant width of the string as argument.

This is useful to pad a numeric string values.

string = "10"
string.zfill(10)

Output:

'0000000010'

A realtime scenario of usage:

In some of the applications we may have a 5 digit numeric string to represent any ID.

In that case, we can pad with zeros for the desired length of the string and do the increment by 1 (convert to int and increase 1).

ID = "15"
ID = ID.zfill(5)
print("Original ID:" + ID)

next_ID = str(int(ID)+1).zfill(5)
print("Next ID:" + next_ID)

Output:

Original ID:00015
Next ID:00016

I hope you enjoyed learning various types of split functions in python.

Lets explore more about Python in future tips.

More interesting Python tips:

A Tip A Day – Python Tip #9: 3 Interesting things about format {}

A Tip A Day – Python Tip #11: Split string using partition, rpartition & splitlines

A Tip A Day – Python Tip #10: 2 reasons to use Python Type Hints

All Other Tips

Other interesting concepts:

SpaCy Vs NLTK – Basic NLP Operations code and result comparison

Best way to Impute NAN within Groups — Mean & Mode

Leave a Reply

Your email address will not be published. Required fields are marked *