random模块&string模块

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

string模块

生成字符

  • whitespace = ' \t\n\r\v\f'
  • ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
  • ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  • ascii_letters = ascii_lowercase + ascii_uppercase
  • digits = '0123456789'
  • hexdigits = digits + 'abcdef' + 'ABCDEF'
  • octdigits = '01234567'
  • punctuation = r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
  • printable = digits + ascii_letters + punctuation + whitespace

猜你喜欢

转载自www.cnblogs.com/leiyiming/p/9044711.html