import random
first = random.randint(1,9)
first = str(first)
n = 5
nrs = [str(random.randrange(10)) for i in range(n-1)]
for i in range(len(nrs)) :
first += str(nrs[i])
print str(first)
import random
num = random.randrange(1, 10**3)
# using format
num_with_zeros = '{:03}'.format(num)
# using string's zfill
num_with_zeros = str(num).zfill(3)
或者,如果你不想把随机数保存为整型数,你也可以把它保存为一行:
'{:03}'.format(random.randrange(1, 10**3))
Python 3.6 + only oneliner:
f'{random.randrange(1, 10**3):03}'
以上产出的实例如下:
026
255
“512”
实现为一个函数,可以支持任何长度的数字,而不仅仅是3:
import random
def n_len_rand(len_, floor=1):
top = 10**len_
if floor > top:
raise ValueError(f"Floor '{floor}' must be less than requested top '{top}'")
return f'{random.randrange(floor, top):0{len_}}'