本文参考转发自:https://www.cnblogs.com/wupeiqi/articles/5501365.html
加密模块 ------ hashlib
用于加密相关的操作,代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法
import hashlib
# ######## md5 ########
hash = hashlib.md5()
# help(hash.update)
hash.update(bytes('admin', encoding='utf-8'))
print(hash.hexdigest())
print(hash.digest())
######## sha1 ########
hash = hashlib.sha1()
hash.update(bytes('admin', encoding='utf-8'))
print(hash.hexdigest())
# ######## sha256 ########
hash = hashlib.sha256()
hash.update(bytes('admin', encoding='utf-8'))
print(hash.hexdigest())
# ######## sha384 ########
hash = hashlib.sha384()
hash.update(bytes('admin', encoding='utf-8'))
print(hash.hexdigest())
# ######## sha512 ########
hash = hashlib.sha512()
hash.update(bytes('admin', encoding='utf-8'))
print(hash.hexdigest())
以上加密算法虽然依然非常厉害,但时候存在缺陷,即:通过撞库可以反解。所以,有必要对加密算法中添加自定义key再来做加密。
import hashlib
# ######## md5 ########
hash = hashlib.md5(bytes('898oaFs09f',encoding="utf-8"))
hash.update(bytes('admin',encoding="utf-8"))
print(hash.hexdigest())
python内置还有一个 hmac 模块,它内部对我们创建 key 和 内容 进行进一步的处理然后再加密
import hmac
h = hmac.new(bytes('898oaFs09f',encoding="utf-8"))
h.update(bytes('admin',encoding="utf-8"))
print(h.hexdigest())
random
import random
print(random.random()) # 产生0到1之间的随机小数
print(random.randint(1, 2)) # 产生[1,2]也就是[a,b]闭区间内的随机整数
print(random.randrange(1, 10)) # 产生[1,10)也就是[a,b)半闭半开区间内的随机整数
随机验证码
import random
checkcode = ''
for i in range(4):
current = random.randrange(0,4)
if current != i:
temp = chr(random.randint(65,90))
else:
temp = random.randint(0,9)
checkcode += str(temp)
print(checkcode)
正则表达式( re )
python中re模块提供了正则表达式相关操作
字符:
. 匹配除换行符以外的任意字符
\w 匹配字母或数字或下划线或汉字
\s 匹配任意的空白符
\d 匹配数字
\b 匹配单词的开始或结束
^ 匹配字符串的开始
$ 匹配字符串的结束
次数:
* 重复零次或更多次
+ 重复一次或更多次
? 重复零次或一次
{n} 重复n次
{n,} 重复n次或更多次
{n,m} 重复n到m次
· match
# match,从起始位置开始匹配,匹配成功返回一个对象,未匹配成功返回None
match(pattern, string, flags=0)
# pattern: 正则模型
# string : 要匹配的字符串
# falgs : 匹配模式
X VERBOSE Ignore whitespace and comments for nicer looking RE's.
I IGNORECASE Perform case-insensitive matching.
M MULTILINE "^" matches the beginning of lines (after a newline)
as well as the string.
"$" matches the end of lines (before a newline) as well
as the end of the string.
S DOTALL "." matches any character at all, including the newline.
A ASCII For string patterns, make \w, \W, \b, \B, \d, \D
match the corresponding ASCII character categories
(rather than the whole Unicode categories, which is the
default).
For bytes patterns, this flag is the only available
behaviour and needn't be specified.
L LOCALE Make \w, \W, \b, \B, dependent on the current locale.
U UNICODE For compatibility only. Ignored for string patterns (it
is the default), and forbidden for bytes patterns.
# demo
# 无分组
r = re.match("h\w+", origin)
print(r.group()) # 获取匹配到的所有结果
print(r.groups()) # 获取模型中匹配到的分组结果
print(r.groupdict()) # 获取模型中匹配到的分组结果
# 有分组
# 为何要有分组?提取匹配成功的指定内容(先匹配成功全部正则,再匹配成功的局部内容提取出来)
r = re.match("h(\w+).*(?P<name>\d)$", origin)
print(r.group()) # 获取匹配到的所有结果
print(r.groups()) # 获取模型中匹配到的分组结果
print(r.groupdict()) # 获取模型中匹配到的分组中所有执行了key的组
# Demo
· search
# search,浏览整个字符串去匹配第一个,未匹配成功返回None
# search(pattern, string, flags=0)
# 无分组
r = re.search("a\w+", origin)
print(r.group()) # 获取匹配到的所有结果
print(r.groups()) # 获取模型中匹配到的分组结果
print(r.groupdict()) # 获取模型中匹配到的分组结果
# 有分组
r = re.search("a(\w+).*(?P<name>\d)$", origin)
print(r.group()) # 获取匹配到的所有结果
print(r.groups()) # 获取模型中匹配到的分组结果
print(r.groupdict()) # 获取模型中匹配到的分组中所有执行了key的组
# demo
· findall
# findall,获取非重复的匹配列表;如果有一个组则以列表形式返回,且每一个匹配均是字符串;如果模型中有多个组,则以列表形式返回,且每一个匹配均是元祖;
# 空的匹配也会包含在结果中
#findall(pattern, string, flags=0)
#demo
# 无分组
r = re.findall("a\w+",origin)
print(r)
# 有分组
origin = "hello alex bcd abcd lge acd 19"
r = re.findall("a((\w*)c)(d)", origin)
print(r)
#Demo
· sub
# sub,替换匹配成功的指定位置字符串
sub(pattern, repl, string, count=0, flags=0)
# pattern: 正则模型
# repl : 要替换的字符串或可执行对象
# string : 要匹配的字符串
# count : 指定匹配个数
# flags : 匹配模式
# demo
# 与分组无关
origin = "hello alex bcd alex lge alex acd 19"
r = re.sub("a\w+", "999", origin, 2)
print(r)
· split
# split,根据正则匹配分割字符串
split(pattern, string, maxsplit=0, flags=0)
# pattern: 正则模型
# string : 要匹配的字符串
# maxsplit:指定分割个数
# flags : 匹配模式
注意:pattern参数是用来进行分割的匹配处,若不匹配则不分割,则得到的是string的原内容,若有匹配则按匹配处进行分割。
>>> re.split("ll","hhh",1) # 不匹配,则返回原string
['hhh']
>>> re.split(r"kk","kkggkkffkk",1) # 最大匹配数为1,所以只对第一处进行分割
['', 'ggkkffkk']
>>> re.split(r"kk","kkggkkffkk",0) # 最大匹配数为0,表示不限最大的分割数
['', 'gg', 'ff', '']
# demo
# 无分组
origin = "hello alex bcd alex lge alex acd 19"
r = re.split("alex", origin, 1)
print(r)
# 有分组
origin = "hello alex bcd alex lge alex acd 19"
r1 = re.split("(alex)", origin, 1)
print(r1)
r2 = re.split("(al(ex))", origin, 1)
print(r2)
# Demo
常用正则表达式
IP:
^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$
手机号:
^1[3|4|5|8][0-9]\d{8}$
邮箱:
[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+
常用正则表达式
简单实现的计算器

"""
author : perfect1t
date : 2018.6.29
若各位读者有更好的建议或不懂可以评论留言哦
"""
import re
def mult_or_div(lt, m_d):
'''
功能 :
lt : 需要进行运算的表达式转换成的列表
m_d: 运算符,可选 "*"或"/"
返回值 :
'''
idx = lt.index(m_d)
if(lt[idx+1] == '-') : # 处理出现图一中的情况
lt[idx+1] = lt[idx+1]+lt[idx+2]
del lt[idx+2]
# ["1","*","2","/","3","+","4"]
if m_d == "*":
ret = float(lt[idx-1]) * float(lt[idx+1])
elif m_d == "/":
ret = float(lt[idx-1]) / float(lt[idx+1])
del lt[idx] # ["1","2","/","3","+","4"]
del lt[idx] # ["1","/","3","+","4"]
lt[idx-1] = str(ret) # ["1*2的结果","/","3","+","4"]
return lt
def add_or_sub(lt):
if lt[0] == '-' : # 第一个是"-",则把其与第二个合并
lt[0] = lt[0] + lt[1]
del lt[1]
ret = float(lt[0])
while(len(lt)>=2):
if len(lt) >= 4:
if(lt[2] == '-') : # 处理出现图一中的情况
lt[2] = lt[2]+lt[3]
del lt[3]
if lt[1] == '+' :
ret += float(lt[2]) # 每次都与lt[2]做加或减操作
else:
ret -= float(lt[2])
del lt[1] # 删除符号
del lt[1] # 删除第2操作数
return ret
def cal(sub_exp):
"""
功能 : 接收一个表达式,返回其结果的字符串形式
sub_exp : 字符串形式的不含有括号表达式
返回值 : 结果的字串表示
"""
# 8*8+8/8-8
ret = re.split(r"([*/+-])",sub_exp,0) # ret = ["8","*","8","+","8","/","8","-","8"]
while '' in ret: # 把列表里的''空串删掉
del ret[ret.index('')]
while True: # 把乘除运算做完为止
if "*" in ret and "/" not in ret:
ret = mult_or_div(ret, "*")
elif "/" in ret and "*" not in ret:
ret = mult_or_div(ret, "/")
elif "*" in ret and "/" in ret :
mul_index = ret.index("*")
div_index = ret.index("/")
if mul_index < div_index : # 同级,从左向右执行
ret = mult_or_div(ret, "*")
else :
ret = mult_or_div(ret, "/")
else :
break;
return add_or_sub(ret)
def select(sour_exp):
prt = re.compile(r"\(([^()]*)\)")
while(True):
ret = re.split(prt, sour_exp, 1)
if len(ret) == 1:
break
else :
sour_exp = ret[0] + str(cal(ret[1])) + ret[2]
print("My calculator's result is : ",cal(sour_exp))
if __name__ == "__main__" :
print("============================ star ============================")
exp = input("Please input your expression : ")
select(exp.replace(" ", ""))
print("Phe eval function's result is : ",eval(exp))
print("============================ end =============================")
运行结果:
============================ star ============================
Please input your expression : 1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )
My calculator's result is : 2776672.6952380957
Phe eval function's result is : 2776672.6952380957
============================ end =============================
调试:

本文介绍Python中hashlib模块的各种加密算法,包括MD5、SHA系列,并演示如何使用这些算法进行数据加密。此外,还详细讲解了Python中re模块的使用方法,包括正则表达式的常见操作如match、search、findall等。
1万+

被折叠的 条评论
为什么被折叠?



