假设我需要一个3位数的电话号码,因此它类似于:
>>> random(3) 563 or >>> random(5) 26748 >> random(2) 56
要获得一个随机的3位数字:
from random import randint randint(100, 999) # randint is inclusive at both ends
(假设您实际上是指三位数,而不是“最多三位数”。)
要使用任意数量的数字:
from random import randint def random_with_N_digits(n): range_start = 10**(n-1) range_end = (10**n)-1 return randint(range_start, range_end) print random_with_N_digits(2) print random_with_N_digits(3) print random_with_N_digits(4)
输出:
33 124 5127