+ 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
24 ответов
+ 7
Here's all correct solutions provided by friends:
https://code.sololearn.com/c7uewxySeA8T/?ref=app
+ 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))}}")
+ 9
#try this way:
for n in range(1, 101):
print(n.__format__("03d")) #width 3, fill 0.
+ 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)
+ 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)
+ 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'
+ 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. 😎
+ 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 :-)
+ 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.
+ 5
Just sharing some relevant links
Please don't mind if you have read them
https://towardsdatascience.com/4-tricks-to-use-JUMP_LINK__&&__python__&&__JUMP_LINK-f-strings-more-efficiently-4f389e890514
https://martinheinz.dev/blog/70
+ 4
+ 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
+ 3
Thank you again Ipang, very instructive links 🙏.
+ 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 🙌
+ 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 ✅
+ 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. 👌
+ 2
Amirreza Amiri I will try to add few more ways to that code
+ 1
Kailash Yandrapu Thank you 👌
+ 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
+ 1
Thank you Yashhhhh. 🙏