[学习笔记]Python 常用函数

本文介绍了Python中使用Random模块生成随机数的方法,包括choice、randrange、random、shuffle及uniform等函数,并通过实例展示了如何生成包含大小写字母、数字和下划线的8位随机密码。此外,还涉及了isinstance函数的用法,用于判断对象是否为特定类型或子类。
部署运行你感兴趣的模型镜像

isinstance(…)
isinstance(object, class-or-type-or-tuple) -> bool

Return whether an object is an instance of a class or of a subclass thereof. With a type as second argument, return whether that is the object’s type. The form using a tuple, isinstance(x, (A, B, …)), is a shortcut for isinstance(x, A) or isinstance(x, B) or … (etc.).

for s in [u'abc', 'abc']:
    print isinstance(s, str)
    print isinstance(s, basestring)
    print isinstance(s, unicode)
#输出结果   
False
True
True
True
True
False

Random生成随机数

函数说明
choice(seq)从序列的元素中随机挑选一个元素,比如random.choice(range(10)),从0到9中随机挑选一个整数。
randrange ([start,] stop [,step])从指定范围内,按指定基数递增的集合中获取一个随机数,基数缺省值为1
random()随机生成下一个实数,它在[0,1)范围内。
shuffle(list)将序列的所有元素随机排序
uniform(x, y)随机生成下一个实数,它在[x,y]范围内。
randint(self,a,b)

练习:生成8位数随机密码,要求大小写数字加下划线

import random
import string

list=[]
for i in range(1,4):                
    a=random.choice(string.digits)
    b=random.choice(string.lowercase)
    c=random.choice(string.uppercase)
    list.append(a)
    list.append(b)
    list.append(c)
del list[0:2]          #取九个元素删掉两个
#print list
list.append("_")       #加上下划线
random.shuffle(list)   #随机排序
password=''.join(list) #拼接成字符

print password

您可能感兴趣的与本文相关的镜像

Python3.9

Python3.9

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值