Python Forum

Full Version: int format for 001 - 999
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Is there a build it method to do the following?

num = 001

num += 1

print(str(num))
result: 002

currently I get an 'Invalid token' error with 001 as a variable

I'm just looking for a way to count 001, 002 - 999. Rather not reinvent the wheel if something already exists.

Thanks!
Numbers with leading zeros are illegal, because doesn't want you to get confused about whether or not they're octal numbers (which are, instead, defined with a leading 0o in python). If you remove the leading zeros, your code will work fine.
(Feb-06-2019, 09:25 PM)jmair Wrote: [ -> ]I'm just looking for a way to count 001, 002 - 999.
Use string formatting f-string is what you should use need 3.6+,version before that use format().
for i in range(1,21):
    print(f"{i:03}") 
Output:
001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016 017 018 019 020
Sometimes, e.g. when it is needed to create/(or load) numbered files, you need to create strings
such as '001', '002' etc. To get this you could use .format method, e.g.
"{:03d}".format(4)
Output:
'004'
========
P.S.
Too late, the same answer already exists...
That's exactly what I needed! Thank you!