# How to make integers start with zeros?

I want a code to output range numbers 1 to 100 but including the zeros before them even in one or two digit ones (like "001, 002, 003, ..., 100" instead of "1, 2, 3, ..., 100"). When I run range(001, 100) I get an error for that zero. Can anyone help please? 🙏 https://code.sololearn.com/cLVVQ4I42P5l/?ref=app

8/18/2022 12:00:20 PM

Amirreza Amiri24 Answers

New AnswerHere's all correct solutions provided by friends: https://code.sololearn.com/c7uewxySeA8T/?ref=app

Amirreza Amiri , to make the output work with various count of digits in max_num, we can calculate the "length" of it. this can be done with: {len(str(max_num))}, and we can implement it direct in the f- string as a nested expression: min_num = int(input()) max_num = int(input()) +1 for num in range(min_num, max_num): print(f"{num:0{len(str(max_num))}}")

#try this way: for n in range(1, 101): print(n.__format__("03d")) #width 3, fill 0.

Amirreza Amiri Or you can check length and add leading 0 for n in range(1, 101): if len(str(n)) == 1: print('00' + str(n)) elif len(str(n)) == 2: print('0' + str(n)) else: print(n)

Since you're into outputting the numbers, I suggest you to look at string method named zfill() https://www.w3schools.com/python/ref_string_zfill.asp Or use f-String for output print( f"{n:03d}" ) (Edited)

Just to show yet another way to do it: width = 3 zeros = '0'*width for i in range(1, 101): print((zeros+str(i))[-width:]) This inserts three zeros on the left of the numeric string, and then slices the string to get the rightmost 3 digits. '000' + '1' = '0001' '0001'[-3:] = '001'

Thanks a lot Lothar. 👌 your code is super automatic zero adder for any desired range of numbers without needing to even type how many zeros we need. 😎

Ipang Jayakrishna🇮🇳 Could either one of you explain when to use. __format__() explicitly or not? Pros and cons? Former easier to implement, latter faster? Amirreza Amiri Gotta love sum codes, thank you for the question and the summary :-)

Korkunç el Gato fstring are simple and easy.. Like this hack : ('0'*3+str(n)) [-3:] the method __format__() I mentioned is from int class magic method. It is overridden method of object class. int, float, str, all have format methods so it compatible. It is internally uses format method of object class, and returns a formatted string.. def __format__(self, format_spec): return format(str(self), format_spec) And support much more specifications... String.format() class is implemented based on c code. I think, this is implemented in C so c code works faster generally. So guessing that's why adapted this. not sure though. All internally uses string convertions. You can use your simple.. For efficiency, am not that much into python.

Just sharing some relevant links Please don't mind if you have read them https://towardsdatascience.com/4-tricks-to-use-python-f-strings-more-efficiently-4f389e890514 https://martinheinz.dev/blog/70

Thank you friends Ipang Jayakrishna🇮🇳 A͢J ❤️🙏. All your methods did exactly solve my problem.

Let's assume we all agree that integers cannot start with zero... You must represent whatever value it is by a string and format the string. I would normally use the AJ method but f-string seems to be shorter and faster

Korkunç el Gato, I recently have finished python for begginers, not fully familiar with format functions. But among these codes I think the faster way is zfill() and the best general method could be f-string. And you're welcome 🙌

this code is useful for taking user inputs for example input 10 output 01 02 03 04 05 06 07 08 09 10 https://code.sololearn.com/c994lpE0hPmG/?ref=app

for n in range(1, 101): if len(str(n)) == 1: print('00' + str(n)) elif len(str(n)) == 2: print('0' + str(n)) hai else: print(n) Done ✅

VAMSI, thank you for your help specially your 3rd method was new for me and the point is it can be used for single numbers rather than ranges. 👌

You can do that in many ways Source code: import random for i in range(0,11): print(str(i).zfill(3)) #way 2 num=random.randint(0,99) print("way-2:",f'{i:03d}') #way 3 addzero=lambda number,zeros:"{0:0{1}d}".format(number,zeros) print("way-3:",addzero(2,3)) https://github.com/vamsi-4-3-4/solutions/blob/main/printzerosbeforeanumber.py