常用函数 name = '{wh}my \t name is {name},age is {age}.'print(name.capitalize()) # 字符串的开头字母大写print(name.center(100, "+")) # 在字符串两边增加'+'号,使整个字符串的个数为50位置print(name.endswith(".")) # 判断是否以X结尾,返回布尔值print(name.expandtabs(30)) # 补充\t的次数\t按一个空格处理,\t一般为2个空格,但在字符串开头或者\n后为4个空格print(name.find("n")) # 查找字符串索引,如果不存在返回-1print(name.index("n")) # 查找元素,如果不存在报错print(name.count("z")) # 查找元素个数,如果不存在返回0print(name.format(wh="nihao,", name="1233", age=100)) # 格式化字符串 print('{ :^10},{:6}'.format('username','password')) #格式化输出扩展 username对应的:^10是右对齐10个字符后输出,password对应:6是默认左对齐6个字符后输出print(name.format_map({ 'wh': 'huanying,', 'name': 'xiaoming', "age": "19"})) # 格式化字符串字典形式print("sadads12313#$".isalnum()) # 是否包含数字和字母print("123".isalpha()) # 是否是英文print("abc".isdigit()) # 是否是数字print(name.decimal()) # 是否是十进制数字print("#¥&*……&*".isidentifier()) # 是否是一个合法的变量名,不常用print("asdadA".islower()) # 判断字符串中是否全部小写print("name".isupper()) # 判断字符串中是否全部是大写print("@#@$#@QsaddsadS Sad ".istitle()) # 判断是否首字母大写,后面小写,标题样式print("___".join([name, "enen", "oo"])) # 拼接字符串 前为拼接符,后为拼接字符串,之后变成一个新的字符串print("SAHD #@OAHDa sd ad".lower()) # 全部变成小写print("sahdk".upper()) # 全部变成大写print(' \t \nmysql\t\n'.lstrip()) # 去除左边的换行和空格print(' \t \nmysql\t\n '.rstrip()) # 去除右边的换行和空格print(' \t \nmysql\t\n '.strip()) # 去掉两边的换行和空格print(" kongge ".isspace()) # 判断是否全是空格 print(" dasds ".split() # 去除两边空格并以字典形式返回print(name.splitlines()) # 以换行符分割字符串 print("mysql is db".replace("mysql", "oracle")) # replace 全部替换 print("mysql is dbisis".rfind("is")) # 返回最右边字符的下标 print("1+2+3+4".split("+")) # 以+分割字符串,以list形式返回 print("1+2+3+4\n5+6+7+8".splitlines()) # 以换行符字符串,以list形式返回 print("abcABC".swapcase()) # 大小写全部反转print("1".zfill(2)) # 将前面字符串中的位数补充0后面填的位数,结果为01print(name.endswith("{age}.")) # 判断字符串结尾是否一致 返回布尔值print(name.startswith("{age}.")) # 判断字符串开头是否一致 返回布尔值print(bin(12)) # 获取整数的二进数形式print(name.ljust(50, '*')) # 在name的左边补充50个* name.rjust()为在右侧str1 = "Runoob example....wow!!!" # maketrans与tranlate的应用l = "12345" # l 和 r 字符串必须数量相同r = "abcde"res = str1.maketrans(r, l) # 把r替换为l在和str1比对,找到相同的并修改print(str1.translate(res) # 打印结果为Runoo2 5x1mpl5....wow!!!print(max(name)) # 返回字符串中的最大字母 优先小写字母 其次大写字母 其次数字 最后是特殊字符 min()最小 print(bool('')) #布尔值判断,例子中返回false,非零或者空为true print(round(3.1415926,2)) #取小数位数,例子中参数为2所以返回3.14 print(sorted([1,3,400,234,23],reverse=True)) #返回排序方式按降序排列,去掉revese按顺序排列 print(any([1,2,3,45])) #返回布尔值,判断list中只要有一个非零非空的值就返回True,否则返回false print(all([1,2,3,45])) #返回布尔值,判断list中只要有一个零或者空的值就返回False,否则返回True print(dir(name)) #查询方法,输出name的所有方法 print(eval("1+1")) #执行一个字符串表达式,返回计算的结果,如例子中返回2,可以把执行简单的python代码 print(exec("print('nihao')")) #执行python代码,常用于浏览器形式的代码编辑软件,但是略微不安全 print(list(map(funcion,L))) #循环调用函数,然后保存函数返回值,放到一个list里,如果不加list返回的是一个生成器 print(list(filter(funcion,L))) #过滤,循环调用函数,如果函数返回的值为真,那么就保存这个值 print(getattr(对象"函数名)) #获取一个对象里面的属性(方法,变量),如果要使用这个方法就返回值加括号() print(hasattr(模块,方法)) #查看模块下是否有该方法,返回布尔值
数据类型转换 a = 1234 print(0x4d2) #其他进制数输入直接转成10进制 print(hex(a)) #转成16进制数 print(oct(a)) #转成8进制数 print(bin(a)) #转成2进制数 print('asd'.encode()) #字符串转成二进制,返回b'asd'; 'asd'.encode()将encode转换成utf-8编码 print(b'asd'.decode()) #二进制转成字符串,decode是bytes类型 print(chr(78)) #0-255内整数作为参数,返回一个对应的ascii码值 print(ord('a')) #将一个字符转换成ascii码 b = ["1234",23,23,213,21341] list(b) #转成列表 tuple(b) #转成元祖 dist(b) #转成字典 int(a) #转成整型 float(a) #转成浮点型 res1= set(b) #返回一个去重,无序,可变集合 res2 = frozenset(b) #返回一个去重,无序,不可变的集合,两者区别:变量不能点出add和remove方法 b_str = str(b) #str()一般是将数值转成字符串(返回一个字符串,包含对象的友好的可打印表示形式。对于字符串,它返回字符串本身) b_repr = repr(b) #repr()是将一个对象转成字符串显示
random模块import randomprint(random.sample([1,3,4,5,6],2)) # 返回一个从0-100中取6位随机数,如位数超出会报错print(random.randrange(100)) # 返回一个从0到100之间的整数,包括0,不包括100print(random.randrange(5,10,2)) # 指定5到10之间并间隔为2整数print(random.randint(1, 3)) # 指定包括1包括3之间的整数print(random.random()) # 打印0到1之间的随机浮点数,包括0print(random.uniform(1.1,32.2)) # 打印1.1到32.2之间随机的浮点数a = [1,23,4,5,6,7]print(random.choice(a)) # 指定a列表或者是元祖中随机取一个元素,列表为空报错random.shuffle(a) print(a) # 打乱a列表中的所有元素,注意输出为a而不能把它变成一个变量random.choices(population, weights=None, *, cum_weights=None, k=1) # 3.6版本新增。从population集群中随机抽取K个元素(可重复)weights是相对权重列表,cum_weights是累计权重,两个参数不能同时存在,k表示个数。random.choices(["红球","黄球","篮球","黑球"], [50,30,15,5], k=1)string模块import stringstring.ascii_letters # 列出所有大小写字母string.ascii_lowercase # 列出所有小写字母string.ascii_uppercase # 列出所有大写字母string.digits # 列出所有数字string.punctuation # 列出所有特殊字符string.printable # 列出所有字符,数字,字母string.hexdigits # 列出所有16进制数string.octdigits # 列出所有8进制数string.whitespace # 列出所有空白符os模块 与操作系统进行交互import os os.system('ls')os.getcwd() # 获取当前工作目录 os.chmod("/local/upload/",7) # 给文件目录/添加权限 os.chdir("../") # 更改当前目录os.curdir() # 当前目录os.pardir() # 父目录os.makedir("/usr/local/tomcat") # 递归创建目录,父目录不存在时自动创建os.removedir("/usr/local/tomcat") # 递归删除空目录,包括父目录os.mkdir("a") # 创建文件夹os.rmdir("a") # 删除空文件夹os.remove("a.txt") # 删除指定文件os.listdir() # 列出指定目录下的所有文件,不传的话是当前目录 .为当前路径os.rename("a","b") # 把a重命名成bos.stat("a.py") # 获取文件信息print(os.sep) # 当前操作系统的路径分隔符print(os.linesep) # 当前操作系统的换行符print(os.pathsep) # 当前系统的环境变量中每个路径的分隔符,linux是:,windows是;print(os.environ) # 当前系统的环境变量print(os.name) # 当前系统名称os.walk("路径") # 递归查询路径下的所有文件及文件夹,三个参数 path(当前目录),dirs(当前目录的所有文件夹,不包括文件),files(当前目录的所有文件,不包括文件夹)os.system('操作系统命令') 或者 os.popen('操作系统命令') # 前者只能将命令执行,获取不到结果,后者可以,res = os.popen('ipconfig').read()print(os.path.abspath(__file__)) # 获取绝对路径print(os.path.getsize('a.txt')) # 取文件大小,单位是字节print(os.path.split("/usr/hehe/hehe.txt")) # 分割路径和文件名print(os.path.dirname("/usr/local")) # 获取父目录print(os.path.basename("/usr/local")) # 获取最后一级,如果是文件显示文件名,如果是目录显示目录名print(os.path.exists("/usr/local")) # 目录/文件是否存在print(os.path.isabs(".")) # 判断是否是绝对路径print(os.path.isfile("/usr/local")) # 判断是否是一个文件print(os.path.isdir("/usr/local")) # 是否是一个路径print(os.path.join("/root",'hehe','a.sql')) # 拼接成一个路径,系统能自动识别linux("/")和windows("\")print(os.path.getatime("len_os.py")) # 输出最近访问时间print(os.path.getmtime("len_os.py")) # 输出最近访问时间print(os.path.getctime("len_os.py")) # 输出文件创建日期 os.access("../test.html", os.F_OK) #os.F_OK参数判断path路径是否存在此文件,返回布尔值 os.access("../test.html", os.R_OK) #os.R_OK参数判断此文件是否可读,返回布尔值 os.access("../test.html", os.W_OK) #os.W_OK参数判断此文件是否可写,返回布尔值 os.access("../test.html", os.X_OK) #os.X_OK参数判断此文件是否可执行,返回布尔值 os.chown(path, uid, gid); #将指定的路径的所有者和组ID更改为数字uid和gid。 os.chroot(path) #方法用于更改当前进程的根目录为指定的目录,使用该函数需要管理员权限,path为设置的根目录路径。
sys模块 与python解释器进行交互import syssys.argv # 命令行参数List,第一个元素是程序本身路径 sys.exit(n) # 退出程序,正常退出时exit(0)sys.version # 获取Python解释程序的版本信息sys.maxint # 最大的Int值sys.path # 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值sys.platform # 返回操作系统平台名称sys.stdout.write('please:') # 向屏幕输出一句话val = sys.stdin.readline()[:-1] # 获取输入的值time,datetime模块 时间有三种表示方式,一种是时间戳、一种是格式化时间、一种是时间元组import time,datetimeprint(time.timezone) # 本地时间和标准时间相差的时间,单位是sprint(time.time()) # 返回当前时间戳 print(time.clock()) # 计算cpu处理执行的时间print(time.sleep(1)) # 休眠,单位秒print(time.gmtime()) # 把时间戳转换成时间元组,如果不传的话,默认取标准时区的时间戳print(time.localtime()) # 把时间戳转换成时间元组,如果不传的话,默认取当前时区的时间戳print(time.mktime(time.localtime())) # 把时间元组转换成时间戳print(time.strftime("%y%m%d %H%M%S")) # 将时间元组转换成格式化输出的字符串print(time.strptime("20160204 191919","%Y%m%d %H%M%S")) # 将格式化的时间转换成时间元组print(time.struct_time) # 时间元组print(time.asctime()) # 时间元转换成格式化时间print(time.ctime()) # 时间戳转换成格式化时间print(datetime.datetime.now()) # 当然时间格式化输出print(datetime.datetime.now()+datetime.timedelta(3)) # 3天后的时间print(datetime.datetime.now()+datetime.timedelta(-3)) # 3天前的时间time.asctime( time.localtime(time.time()) ) # 可读格式获取现在时间 import calendar calendar.month(2021, 11) # 获取2021年11月的日历,先导入import calendar模块str类型的日期转换为时间戳tss1 = '2018-10-10 23:40:00'#字符型时间格式timeArray = time.strptime(tss1, "%Y-%m-%d %H:%M:%S")#转成时间数组,所有时间数组都可以.出方法来调用所需要的字段timeStamp = int(time.mktime(timeArray))#转成时间戳修改str类型的日期格式tss2 = "2013-10-10 23:40:00"timeArray = time.strptime(tss2, "%Y-%m-%d %H:%M:%S")otherStyleTime = time.strftime("%Y/%m/%d %H:%M:%S", timeArray)时间戳转换为指定格式的日期 #timetimeStamp = 1381419600timeArray = time.localtime(timeStamp)otherStyleTime = time.strftime("%Y--%m--%d %H:%M:%S", timeArray)#datetimetimeStamp = 1381419600dateArray = datetime.datetime.utcfromtimestamp(timeStamp)otherStyleTime = dateArray.strftime("%Y--%m--%d %H:%M:%S")时间戳变成指定格式#timenow = int(time.time()) # 1533952277timeArray = time.localtime(now)otherStyleTime = time.strftime("%Y--%m--%d %H:%M:%S", timeArray)#datetimenow = datetime.datetime.now()otherStyleTime = now.strftime("%Y--%m--%d %H:%M:%S") configparser模块 通常用作配置文件的增删改查 #生成conf文件
import configparser conf = configparser.ConfigParser() conf['mysql'] = { 'user': 'nihao', 'passwd': 123456, 'port': 3306 } conf['redis'] = {} conf['redis']['user'] = 'nihao' conf['redis']['passwd'] = '123456' conf['redis']['port'] = '6379' with open('conf.txt', 'w') as configfile: conf.write(configfile) #读取conf文件
import configparser conf = configparser.ConfigParser() conf.read('conf.txt') #读取conf文件 sec = conf.sections() #获取所有父节点值 opt = conf.options('mysql') #获取指定父节点下的所有子节点key item = conf.items('redis') #获取指定父节点下的所有子节点的key,values v_int = conf.getint('redis', 'passwd') #获取指定节点的int数据 v_boolean = conf.getboolean('redis', 'tpye') #获取指定节点的布尔值数据 v_float = conf.getfloat('redis', 'salary') #获取指定节点的浮点数据 v_all = conf.get('redis', 'all') #获取指定节点的所有类型数据
#修改conf文件
import configparser conf = configparser.ConfigParser() conf.read('conf.txt') #读取conf文件 conf.add_section('db') #添加一个父类节点 conf.add_section('123') conf.remove_section('123') #删除一个父节点 conf.set('db','db_username','rainbol') #添加一个子节点并赋值 conf.set('db','db_password','123456') conf.remove_option('mysql','user') #删除一个子节点 conf.remove_option('mysql','passwd') conf.set('mysql','username','root') conf.set('mysql','password','654321') conf.clear() #清空配置文件 conf.write(open('conf.txt','w',encoding='utf-8')) #修改完成写入配置文件 itsdangerous模块 #一种的加密方式,程序解析加密和加密字符串,可以记录TTL和盐值 salt = 'saO)(&)H' #设置盐值 t = itsdangerous.TimedJSONWebSignatureSerializer(salt,expires_in=600)#指定参数,第一个是盐值,第二个是TTL加密过期时间 res = t.dumps({ 'username':'rainbol','password':'123456'})#设置加密的字典 print(res.decode())#取加密信息
session = 'eyJhbGciOiJIUzUxMiIsImlhdCI6MTU0MjAwMTcwNCwiZXhwIjoxNTQyMDAyMzA0fQ.eyJ1c2VybmFtZSI6IkNoZW56dWFueWkxMjMiLCJwYXNzd29yZCI6IkN6eTEyMzQhISJ9. tOdU5gNQdIVONPoD5DLxsW4lRcDX_n3Bg82RR5C48uXT5JhW7Z_UYqpZYd16p9tlT7moXM-T0Son07_KGaBJvA'
res = t.loads(session)#解析加密信息,如果加密信息不正确会报错 print(res) glod模块 #过滤目录 print(glob.glob('*.py'))#返回一个list,括号中填写过滤条件,*.py表示取结尾为py的文件
platform模块 #判断操作系统,如os,linux,windows
import platform import os if platform.system().lower()== 'linux': os.system('ls') elif platform.system().lower()=='windows': os.system('dir') else: pass
gevent模块 #基于greenlet封装,避免多线程切换导致io执行效率降低import geventfrom gevent import monkeymonkey.patch_all()def run(name, url): r = requests.get(url) open(name + '.html', 'wb').write(r.content)url = { 'rainbol01': 'https://www.cnblogs.com/RainBol/', 'rainbol02': 'https://www.cnblogs.com/RainBol/p/9505438.html', 'rainbol03': 'https://www.cnblogs.com/RainBol/p/10077388.html' }for name, url in url.items(): g = gevent.spawn(run, name, url) # 启动 g.join() # 等待并切换
logger模板[1] #日志是一种可以追踪某些软件运行时所发生事件的方法。python封装好了我们可以使用生成的日志报告框架 import logginglogging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a,%d %b %Y %H:%M:%S', filename='test.log', filemode='w')# level 级别 = logging.DEBUG 设置debug级别 # format 格式完全可以自定义 # datefmt 根据format中的asctime来设置指定自定义时间 # filename 设置文件输出格式,如果如果去掉filename和filemode将以屏幕输出格式# filemode 文件模式 # 'w'记录到文件日志中,在w模式下,相当于打开文件的写操作,会覆盖之前的记录覆盖 # 'a'记录到文件日志中,在a模式下,相当于打开文件的追加操作 # format固定变量格式'''%(name)s 打印日志名称 %(levelno)s 打印日志级别的数值 %(levelname)s 打印对应filename参数中的设置的log路径 %(pathname)s 打印当前执行程序的路径 %(filename)s 打印文件名%(module)s 打印日志输出函数的模块名%(lineno)d 记录执行代码行号 %(funcName)s 由哪个function发出的log, 调用日志输出函数的函数名%(created)f 当前时间,用UNIX标准的表示时间的浮点数表示; 日志事件发生的时间--时间戳,就是当时调用time.time()函数返回的值%(asctime)s 对应datefmt参数中设置的时间 %(msecs)d 日志事件发生事件的毫秒部分%(relativeCreated)d 日志记录创建时的时间(以毫秒为单位),与加载日志模块的时间(通常在应用程序启动时)相关 %(thread)d 打印线程id %(threadName)s 打印线程名称 %(process)d 打印进程id %(message)s 打印日志信息 '''# 日志级别 critical > error > warning > info > debug logging.debug('this is debug message')logging.info('this is info message')logging.warning('this is warning message')logging.error('this is error message')logging.critical('this is critical message')
logger模板[2] #既想输出屏幕还输出到文件用此格式import logging#创建四个对象logger = logging.getLogger()#拿到一个logger对象filer = logging.FileHandler('test.log')#创建一个把test.log路径放到FileHandler文件输出对象stream = logging.StreamHandler()#创建一个屏幕输出对象formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')#创建一个把format输出到Formatter中的对象filer.setFormatter(formatter)#fh文件添加输出格式stream.setFormatter(formatter)#ch屏幕添加输出格式#为logger添加文件输出格式和屏幕输出格式logger.addHandler(filer)logger.addHandler(stream)logger.setLevel(logging.DEBUG)#指定日志级别设置为DEBUGlogger.debug('this is debug message')logger.info('this is info message')logger.warning('this is warning message')logger.error('this is error message')logger.critical('this is critical message') 参考:
hashlib模块 import hashlibpassword1 = '123456'res = password1.encode()#将密码转出二进制,password2 = b'123456'或者直接加bm = hashlib.md5(res)#进行md5加密print(m.hexdigest())#显示md5加密加盐:二级加密,保证数据的安全,我们会在md5加密代码前加上一个特定的字符串,如123456helloworld,输入密码为123456,进过加盐对123456helloworld进行md5加密,当用户登录输入密码,代码自动在用户输入密码后加盐,转出md5与数据库匹配 除了MD5还有sha.224,sha256更安全,由于md5算法是不可逆的,所以按照实际业务来实现算法 双重加密 加密两次,我们使用os.urandom(n) #表示一个生成n个字节随机字符串,当然每次打印生成的结果肯定是不一样的 uuid加密 import uuid res=uuid.uuid4() #根据机器号时间等信息生成的随机序列号 #e6684777-5166-455f-8c48-c6f5f3e79d2cimport osfrom hashlib import md5req = os.urandom(24)res = md5(os.urandom(24)).hexdigest()print(res)#002747ea4bb0852767c9449307f8da93
importlib模块 #实现动态导入模块并执行 import importlibmode = 'libtest.importlib_test' #mode为libtest文件下的importlib_test.py文件fuc = 'run' #文件中的run函数名称moc = importlib.import_module(mode) #将mode变量导入,该模块会拿到py文件对象res = getattr(moc,fuc) #再通过getattr传入对象和函数名称res()#最后执行模块方法
heapq模块 #从一个集合中查找最大最小的N个元素——Python heapq 堆数据结构import heapqnum = [23,213,1,23,2,23,24,5,345,34.324,5,3,52]max= heapq.nlargest(3,num)#显示列表中的最大前三个min = heapq.nsmallest(3,num)#显示列表中的最小前三个# heapq.nlargest(n, iterable[, key])第三参数key的使用portfolio = [ { 'name': 'IBM', 'shares': 100, 'price': 91.1}, { 'name': 'AAPL', 'shares': 50, 'price': 543.22}, { 'name': 'FB', 'shares': 200, 'price': 21.09}, { 'name': 'HPQ', 'shares': 35, 'price': 31.75}, { 'name': 'YHOO', 'shares': 45, 'price': 16.35}, { 'name': 'ACME', 'shares': 75, 'price': 115.65} ]print(heapq.nlargest(3,portfolio,lambda x:x['shares']))#从例子中可以看出x['shares']可以取关键字shares值的数据作为排列规则,并且再取整行数据#>>[{'name': 'FB', 'shares': 200, 'price': 21.09}, {'name': 'IBM', 'shares': 100, 'price': 91.1}, {'name': 'ACME', 'shares': 75, 'price': 115.65}]
callable() def hanshu(): passprint(callable(hanshu))#trueprint(callable('我不是函数'))#false
版权声明:本文原创发表于 博客园,作者为 本文欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则视为侵权。