Python: Create Values with Leading 0s

June 21, 2013 — Leave a comment

Zipcodes have 5 integers in them and also have leading zeros. You can’t do the following:

for zipcode in xrange(0,99999):
    print zipcode

The above code will just print numbers 0-99999, when you really want 00000-99999.

To get the leading zeros, you need to use zfill().

for zipcode in xrange(10000):
    # To create zipcodes with leading 0's
    zipcode = str(zipcode).zfill(5)  
    print zipcode

Mike

Posts Twitter Facebook

My name is Michael Le, and I am a web developer.

No Comments

Be the first to start the conversation.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.