Python Forum
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
int format for 001 - 999
#1
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!
Reply
#2
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.
Reply
#3
(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
Reply
#4
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...
Reply
#5
That's exactly what I needed! Thank you!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020