day5-随机数相关:random模块&string模块

一、概述

随机数在程序设计中的属于比较基础的内容,主要用于验证场景(如验证码,生成账号对应的密码等),今天结合random模块和string模块来谈谈python中随机数那些事儿。

二、随机数实现相关模块

2.1 random模块

  • random.random()
    返回一个随机浮点数

      1 >>> import random
      2 >>> print(random.random())
      3 0.7998107271564998
      4 >>> print(random.random())
      5 0.7837981404514991
  • random.randint(a,b)
    随机返回a到b之间的一个整型数,注意包括b

      1 >>> print(random.randint(1,3))
      2 1
      3 >>> print(random.randint(1,3))
      4 2
      5 >>> print(random.randint(1,3))
      6 1
      7 >>> print(random.randint(1,3))
      8 3
  • random.randrange(start, stop, step=1)
    返回一个随机整型数,但不包括stop这个值,start和step为可选项,默认值分别为0和1

      1 >>> print(random.randrange(5,step=2))
      2 1
      3 >>> print(random.randrange(5,step=2))
      4 0
      5 >>> print(random.randrange(5,step=2))
      6 1
      7 >>> print(random.randrange(5,step=2))
      8 3
      9 >>> print(random.randrange(1,5,step=2))
     10 1
     11 >>> print(random.randrange(1,5,step=2))
     12 1
     13 >>> print(random.randrange(1,5,step=2))
     14 1
     15 >>> print(random.randrange(1,5,step=2)) #如果start和stop之间的区间太小,然后有设定了start和step,实际取值范围很有限
     16 3
  • randome.sample(population, k)
    从Population中随机抽取k个值来,以列表形式输出。注意这里的Population必须为一个序列或列表。

      1 >>> print(random.sample([1,2,3,4,5],3))
      2 [3, 2, 5]
      3 >>> print(random.sample(‘asldf9090asm‘,5))
      4 [‘a‘, ‘l‘, ‘d‘, ‘9‘, ‘0‘]
      5 >>> print(‘‘.join(random.sample(‘asldf9090asm‘,5))) #通过join拼接输出即可得到一般的随机数格式
      6 0da09

2.2 string模块

  • string.ascii_letters
    返回包括所有字母在内的大小写字符串

      1 >>> import string
      2 >>> string.ascii_letters
      3 ‘abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ‘
  • string.ascii_lowercase
    返回包含所有小写字母在内的字符串

      1 >>> import string
      2 >>> string.ascii_lowercase
      3 ‘abcdefghijklmnopqrstuvwxyz‘
  • string.ascii_uppercase
    返回包含所有大写字母在内的字符串

      1 >>> import string
      2 >>> string.ascii_uppercase
      3 ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ‘
      4 >>>
  • string.digits
    返回0-9数字字符串

      1 >>> import string
      2 >>> string.digits
      3 ‘0123456789‘
  • string.punctuation
    以字符串形式返回所有特殊字符

      1 >>> import string
      2 >>> string.punctuation
      3 ‘!"#$%&\‘()*+,-./:;<=>[email protected][\\]^_`{|}~‘

三、实战生成随机数

  • 结合random和string实现

      1 >>> import string,random
      2 >>> string2=random.sample(string.ascii_letters+string.punctuation,12)
      3 >>> print(‘‘.join(string2))
      4 _oCSe,)dcBm|
      5 >>>
  • 增强版
    上述程序虽然基本实现了生成随机数的需求,但是随机数的随机性感觉还是比较low,下面来一个增强版的

      1 import random,string
      2 checkcode=‘‘
      3 string1=‘[email protected]#$%&‘ #特殊字符
      4 for i in range(4):
      5     current = random.randrange(0,4)
      6     if current != i:
      7         #temp = chr(random.randint(65,99))
      8         temp = ‘‘.join(random.sample(string.ascii_letters+string1, 3))
      9     else:
     10         temp = random.randrange(0,9)
     11     checkcode += str(temp)
     12
     13 print(checkcode)
     14
     15 运行结果:
     16 Lbksxh#ZB%ar

    增强版程序的不足之处在于随机数的长度不固定,有待完善…

原文地址:https://www.cnblogs.com/linupython/p/8110875.html

时间: 2024-08-08 09:40:58

day5-随机数相关:random模块&string模块的相关文章

Python_python模块(json、os、sys、random、string、time、hashlib)

# json.os.sys.random.string.time.hashlib# json模块import json # json串就是字符串.d = { 'car': {'color': 'red', 'price': 100, 'count': 50}, '挨粪叉': {'color': 'red', 'price': 100, 'count': 50}, '挨粪叉1': {'color': 'red', 'price': 100, 'count': 50},} res = json.du

2018年04月25日 logging模块、os.name模块、sys模块、random模块、string模块

logging模块 官方文档:https://docs.python.org/3.6/library/logging.html ''' 日志记录模块 日志的几个级别 debug info warning error critical ''' import logging # logging.basicConfig(level=logging.DEBUG) logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename

random &amp;&amp; string模块

random import random # 0到1随机浮点数 ret=random.random() # [1,3]双闭合区间随机int型数 ret=random.randint(1,3) # [1,3)左开右闭合区间随机int型数 ret=random.randrange(1,3) # 随机在指定区间选择数 ret=random.choice([11,22,33,44,55]) # 指定随机区间并且指定随机选择个数 ret=random.sample([11,22,33,44,55],2)

python 常用模块 time random os模块 sys模块 json &amp; pickle shelve模块 xml模块 configparser hashlib subprocess logging re正则

python 常用模块 time random os模块 sys模块 json & pickle shelve模块 xml模块 configparser hashlib  subprocess logging re正则 转自老男孩老师Yuan:http://www.cnblogs.com/yuanchenqi/articles/5732581.html 模块&包(* * * * *) 模块(modue)的概念: 在计算机程序的开发过程中,随着程序代码越写越多,在一个文件里代码就会越来越长,

Python 常用模块(1) -- collections模块,time模块,random模块,os模块,sys模块

主要内容: 一. 模块的简单认识 二. collections模块 三. time时间模块 四. random模块 五. os模块 六. sys模块 一. 模块的简单认识 模块: 模块就是把装有特定功能的代码进行归类的结果引入模块的方式: (1) import 模块 (2) from 位置 import 模块 二. collections模块 collections模块主要封装了一些关于集合类的相关操作. 如我们学过的iterable,iterator等等.除此以外, collections还提

Python学习之String模块详解

本文和大家分享的主要是python 中String 模块相关内容,一起来看看吧,希望对大家 学习python有所帮助. String 模块包含大量实用常量和类,以及一些过时的遗留功能,并还可用作字符串操作. 1. 常用方法 str.capitalize() 把字符串的首字母大写 str.center(width) 将原字符串用空格填充成一个长度为 width 的字符串,原字符串内容居中 str.count(s) 返回字符串 s 在 str 中出现的次数 str.decode(encoding='

Python进阶(十)----规范化格式目录, time模块, datatime模块,random模块,collection模块(python额外数据类型)

Python进阶(十)----规范化格式目录, time模块, datatime模块,random模块,collection模块(python额外数据类型) 一丶规范化格式目录 六个目录: #### 对某某项目进行一个标准化的开发,进行规范化. #bin : 启动项目程序的主入口 #conf : 项目的配置文件 #core : 主要逻辑(业务逻辑) #db : 存放数据() #lib : 辅助文件(存放公共的一些方法) #README : 项目文档说明 ? 二丶time模块(时间模块) 时间的三

Python标准库笔记(1) — string模块

String模块包含大量实用常量和类,以及一些过时的遗留功能,并还可用作字符串操作. 1. 常用方法 常用方法 描述 str.capitalize() 把字符串的首字母大写 str.center(width) 将原字符串用空格填充成一个长度为width的字符串,原字符串内容居中 str.count(s) 返回字符串s在str中出现的次数 str.decode(encoding=’UTF-8’,errors=’strict’) 以指定编码格式解码字符串 str.encode(encoding=’U

Drupal cache相关的几个模块

https://www.drupal.org/project/purge https://www.drupal.org/project/expire https://www.drupal.org/project/cfpurge https://www.drupal.org/project/varnish https://www.drupal.org/project/memcache https://www.drupal.org/project/memcache_storage https://w