Python經常使用模塊——random隨機模塊

Python經常使用模塊——random隨機模塊

程序中有不少地方都須要用到隨機字符,好比登陸網站的隨機驗證碼,經過random模塊能夠很容易生成隨機字符串。python

>>> random.randrange(1,10) #返回1-10之間的一個隨機數,不包括10

>>> random.randint(1,10) #返回1-10之間的一個隨機數,包括10

>>> random.randrange(0, 100, 2) #隨機選取0到100間的偶數,即步長爲2

>>> random.random()  #返回一個隨機浮點數

>>> random.choice('abce3#$@1') #返回一個給定數據集合中的隨機字符
'#'

>>> random.sample('abcdefghij',3)  #從多個字符中選取特定數量的字符
['a', 'd', 'b']

#生成隨機字符串
>>> import string 
>>> ''.join(random.sample(string.ascii_lowercase + string.digits, 6)) 
'4fvda1'

#洗牌
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> random.shuffle(a)
>>> a
[3, 0, 7, 2, 1, 6, 5, 8, 9, 4]
相關文章
相關標籤/搜索