I'm trying to make a number guesser that starts from 000001 and counts up all the way to 999999 how can I do that?
Asked
Active
Viewed 1,105 times
-3
-
do you mean, "if i input a number, and an n, you want to print the output containing n digits?" – Tharun K Feb 20 '21 at 07:44
-
1You can't do this with actual numbers like `int` or `float` but if you are able to use strings, then you can use string formatting to left-pad the numbers with a 0. – ddejohn Feb 20 '21 at 07:45
2 Answers
0
For dynamically choosing the pad-width:
>>> num_digits = 6
>>> f"{str(x).rjust(num_digits, '0')}"
'000003'
>>> num_digits = 3
>>> f"{str(x).rjust(num_digits, '0')}"
'003'
>>> x = 521
>>> f"{str(x).rjust(num_digits, '0')}"
'521'

ddejohn
- 8,775
- 3
- 17
- 30
-
Seems you've edited your post, and now it's clear that dynamically choosing the pad-width is not what you need, so either use Hata's answer or slightly cleaner: `f"{x:>06}"` – ddejohn Feb 20 '21 at 08:14