By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,331 Members | 1,109 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,331 IT Pros & Developers. It's quick & easy.

making a list with leading zeros

P: 39
I am using the range function tomake a list of jpgs between 1 and 200 but want there to be leading zeros in the list.
My current code is like this.

Expand|Select|Wrap|Line Numbers
  1. myList=[]
  2.  
  3. for i in range (0,10):
  4.      myList.append (("00%s.jpg)%(i))
  5.  
  6. for i in range (10,100):
  7.      myList.append (("0%s.jpg)%(i))
  8.  
  9. for i in range (100,200):
  10.      myList.append (("%s.jpg)%(i))
  11.  
the result is as follows:

000.jpg
001.jpg
etc.

It basically adds the leading zeros in three different steps. It works but I wanted to know if there is a more elegant solution.
Thanks
May 2 '13 #1

✓ answered by bvdet

String formatting can accomplish that on one range.
Expand|Select|Wrap|Line Numbers
  1. >>> for i in range(1, 201):
  2. ...     print "%03d.jpg" % (i)
  3. ...     
  4. 001.jpg
  5. 002.jpg
  6. 003.jpg
  7. 004.jpg
  8. 005.jpg
  9. 006.jpg
  10. 007.jpg
  11. 008.jpg
  12. 009.jpg
  13. 010.jpg
  14. 011.jpg
  15. 012.jpg
  16. 013.jpg
  17. 014.jpg
  18. 015.jpg
  19. 016.jpg
  20. 017.jpg
  21. 018.jpg
  22. 019.jpg
  23. 020.jpg
  24. 021.jpg
  25. 022.jpg
  26. 023.jpg
  27. 024.jpg
  28. 025.jpg
  29. ....snip....
  30. 199.jpg
  31. 200.jpg
  32. >>> 

Share this Question
Share on Google+
2 Replies

Rabbit
Expert Mod 10K+
P: 12,441
1) Append 2 zeroes to the string.
2) Take the right 3 characters.
3) Append the .jpg.
May 2 '13 #2

bvdet
Expert Mod 2.5K+
P: 2,851
String formatting can accomplish that on one range.
Expand|Select|Wrap|Line Numbers
  1. >>> for i in range(1, 201):
  2. ...     print "%03d.jpg" % (i)
  3. ...     
  4. 001.jpg
  5. 002.jpg
  6. 003.jpg
  7. 004.jpg
  8. 005.jpg
  9. 006.jpg
  10. 007.jpg
  11. 008.jpg
  12. 009.jpg
  13. 010.jpg
  14. 011.jpg
  15. 012.jpg
  16. 013.jpg
  17. 014.jpg
  18. 015.jpg
  19. 016.jpg
  20. 017.jpg
  21. 018.jpg
  22. 019.jpg
  23. 020.jpg
  24. 021.jpg
  25. 022.jpg
  26. 023.jpg
  27. 024.jpg
  28. 025.jpg
  29. ....snip....
  30. 199.jpg
  31. 200.jpg
  32. >>> 
May 2 '13 #3

Post your reply

Sign in to post your reply or Sign up for a free account.