Creating random numbers with a leading 0 in python 3x

匆匆过客 提交于 2020-03-23 06:52:04

问题


In Python 3x, is there a way to generate a random number of a fixed number of digits that could return a 0 in the first place or first two places? e.g. 005 or 059 rather than 5 and 59?

I am creating a game where players need to enter a randomly created 3 digit code (found elsewhere in the game). Ideally it would be chosen from 000 - 999.

random.randint(0,999) won't provide the output I am after.

The only solution I can come up with is long winded (generating 3 numbers between 0 and 9, converting to strings and combining) and I would like to know if there is a more direct method:

import random

digit1 = str(random.randint(0,9))
digit2 = str(random.randint(0,9))
digit3 = str(random.randint(0,9))

code = digit1 + digit2 + digit3

This method would allow me to then compare to the user's input code but I would like to generate the number directly if possible.

EDIT: To clarify, I'd like to know if there is a way to generate a number that is of a predetermined number of digits, that can have a '0' in one or more of the leading digits, without having to convert the number to a string in order to format. Nicest way to pad zeroes to string helps although I am not trying to print the random number, but rather compare it to a use input (e.g. '0560').


回答1:


You can try the following:

import random

min = 0
max = 999
digits = [str(random.randint(min, max)) for i in range(5)]
digits = [(len(str(max))-len(digit))*'0'+digit for digit in digits]

>>> digits
['099', '142', '684', '881', '734']
>>> 


来源:https://stackoverflow.com/questions/30251588/creating-random-numbers-with-a-leading-0-in-python-3x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!