+ 5

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

18th Aug 2022, 12:00 PM
Amirreza
24 ответов
+ 7
Here's all correct solutions provided by friends: https://code.sololearn.com/c7uewxySeA8T/?ref=app
18th Aug 2022, 1:32 PM
Amirreza
+ 10
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))}}")
18th Aug 2022, 3:26 PM
Lothar
Lothar - avatar
+ 9
#try this way: for n in range(1, 101): print(n.__format__("03d")) #width 3, fill 0.
18th Aug 2022, 12:08 PM
Jayakrishna 🇮🇳
+ 9
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)
18th Aug 2022, 12:13 PM
A͢J
A͢J - avatar
+ 8
Since you're into outputting the numbers, I suggest you to look at string method named zfill() https://www.w3schools.com/JUMP_LINK__&&__python__&&__JUMP_LINK/ref_string_zfill.asp Or use f-String for output print( f"{n:03d}" ) (Edited)
18th Aug 2022, 12:03 PM
Ipang
+ 8
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'
18th Aug 2022, 12:42 PM
Brian
Brian - avatar
+ 5
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. 😎
18th Aug 2022, 5:37 PM
Amirreza
+ 5
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 :-)
18th Aug 2022, 5:49 PM
Korkunç el Gato
Korkunç el Gato - avatar
+ 5
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.
18th Aug 2022, 7:02 PM
Jayakrishna 🇮🇳
19th Aug 2022, 3:09 AM
Ipang
+ 4
Thank you friends Ipang Jayakrishna🇮🇳 A͢J ❤️🙏. All your methods did exactly solve my problem.
18th Aug 2022, 12:20 PM
Amirreza
+ 4
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
19th Aug 2022, 4:22 AM
Kailash Yandrapu
+ 3
Thank you again Ipang, very instructive links 🙏.
19th Aug 2022, 1:14 PM
Amirreza
+ 2
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 🙌
18th Aug 2022, 6:22 PM
Amirreza
+ 2
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 ✅
20th Aug 2022, 8:46 AM
DivyanshuYash
DivyanshuYash - avatar
+ 2
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. 👌
20th Aug 2022, 1:49 PM
Amirreza
+ 2
Amirreza Amiri I will try to add few more ways to that code
20th Aug 2022, 2:11 PM
VAMSI
VAMSI - avatar
+ 1
Kailash Yandrapu Thank you 👌
19th Aug 2022, 1:22 PM
Amirreza
+ 1
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
19th Aug 2022, 2:30 PM
VAMSI
VAMSI - avatar
+ 1
Thank you Yashhhhh. 🙏
20th Aug 2022, 5:50 PM
Amirreza