分享

Python随机数与随机字符串详解

 nxhujiee 2017-12-20

随机整数:

1
2
3
>>> import random
>>> random.randint(0,99)
21

随机选取0到100间的偶数:

1
2
3
>>> import random
>>> random.randrange(01012)
42

随机浮点数:

1
2
3
4
5
>>> import random
>>> random.random() 
0.85415370477785668
>>> random.uniform(110)
5.4221167969800881

随机字符:

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

多个字符中选取特定数量的字符:

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

多个字符中选取特定数量的字符组成新字符串:

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

随机选取字符串:

1
2
3
>>> import random
>>> random.choice ( ['apple''pear''peach''orange''lemon'] )
'lemon'

洗牌:

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

random的函数还有很多,此处不一一列举,

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多