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中的数据类型和控制流

上一篇文章中我们介绍了 python 语言的几个特点,并在最后留了一个问题,python 除了上下执行以外有没有其他的执行方式。 今天我们就来介绍 python 中的数据类型和控制流。...

python求素数示例分享

复制代码 代码如下:# 判断是否是素数def is_sushu(num): res=True for x in range(2,num-1):  ...

Python使用Matplotlib模块时坐标轴标题中文及各种特殊符号显示方法

Python使用Matplotlib模块时坐标轴标题中文及各种特殊符号显示方法

本文实例讲述了Python使用Matplotlib模块时坐标轴标题中文及各种特殊符号显示方法。分享给大家供大家参考,具体如下: Matplotlib中文显示问题——用例子说明问题 #...

mac下如何将python2.7改为python3

mac下如何将python2.7改为python3

1.查看当前电脑python版本 python -V  // 显示2.7.x 2.用brew升级python brew update python  3.如果安装...

Python 内置变量和函数的查看及说明介绍

Python 内置变量和函数的查看及说明介绍

Python 解释器内置了一些常量和函数,叫做内置常量(Built-in Constants)和内置函数(Built-in Functions),我们怎么在 查看全部内置常量和函数的名字...