Python常用随机数与随机字符串方法实例

yipeiwu_com6年前Python基础

随机整数:

复制代码 代码如下:

>>> import random
>>> random.randint(0,99)
21

随机选取0到100间的偶数:
复制代码 代码如下:

>>> import random
>>> random.randrange(0, 101, 2)
42

随机浮点数:
复制代码 代码如下:

>>> import random
>>> random.random()
0.85415370477785668
>>> random.uniform(1, 10)
5.4221167969800881

随机字符:
复制代码 代码如下:

>>> import random
>>> random.choice('abcdefg&#%^*f')
'd'

多个字符中选取特定数量的字符:
复制代码 代码如下:

>>> import random
random.sample('abcdefghij',3)
['a', 'd', 'b']

多个字符中选取特定数量的字符组成新字符串:
复制代码 代码如下:

>>> import random
>>> import string
>>> string.join(random.sample(['a','b','c','d','e','f','g','h','i','j'], 3)).r
eplace(" ","")
'fih'

随机选取字符串:
复制代码 代码如下:

>>> import random
>>> random.choice ( ['apple', 'pear', 'peach', 'orange', 'lemon'] )
'lemon'

洗牌:
复制代码 代码如下:

>>> import random
>>> items = [1, 2, 3, 4, 5, 6]
>>> random.shuffle(items)
>>> items
[3, 2, 5, 6, 4, 1]

random的函数还有很多,此处不一一列举,
参考资料: http://docs.python.org/lib/module-random.html

相关文章

python实现微信接口(itchat)详细介绍

前言 itchat是一个开源的微信个人号接口,使用python调用微信从未如此简单。使用不到三十行的代码,你就可以完成一个能够处理所有信息的微信机器人。当然,该api的使用远不止一个机器...

Python 导入文件过程图解

Python 导入文件过程图解

1、同级目录下调用 若在程序 testone.py 中导入模块 testtwo.py , 则直接使用 【import testtwo 或 from testtwo import *】...

Python实现从SQL型数据库读写dataframe型数据的方法【基于pandas】

本文实例讲述了Python实现从SQL型数据库读写dataframe型数据的方法。分享给大家供大家参考,具体如下: Python的pandas包对表格化的数据处理能力很强,而SQL数据库...

Python使用Pickle库实现读写序列操作示例

本文实例讲述了Python使用Pickle库实现读写序列操作。分享给大家供大家参考,具体如下: 简介 pickle模块实现了用于对Python对象结构进行序列化和反序列化的二进制协议。“...

python elasticsearch从创建索引到写入数据的全过程

python elasticsearch从创建索引到写入数据的全过程

python elasticsearch从创建索引到写入数据 创建索引 from elasticsearch import Elasticsearch es = Elasticsea...