Kwan-C

Python常用模块——random随机模块

程序中有很多地方都需要用到随机字符,比如登录网站的随机验证码,通过random模块可以很容易生成随机字符串。

>>> 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]

分类:

技术点:

相关文章:

  • 2021-10-19
  • 2021-01-16
  • 2019-07-29
  • 2021-10-19
  • 2021-10-19
  • 2022-01-03
  • 2021-04-20
  • 2021-08-16
猜你喜欢
  • 2021-10-19
  • 2021-11-06
  • 2020-01-27
  • 2021-10-19
  • 2018-12-08
  • 2021-10-19
  • 2021-11-30
相关资源
相似解决方案