(董付国)Python 学习笔记---Python字符串与正则表达式(2)

4.1.3 字符串常量

  • Python标准库string中定义数字字符、标点符号、英文字母、大小写字母等常量
>>> import string
>>> string.digits
'0123456789'
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  • 随机密码生成原理
>>> import string
>>> x = string.digits + string.ascii_letters + string.punctuation
>>> x
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> import random
>>> ''.join([random.choice(x) for i in range(8)])
'r=PU~4@<'
>>> ''.join([random.choice(x) for i in range(8)])
'P7c@r@*.'
>>> ''.join([random.choice(x) for i in range(8)])
'=*-F9<_}'
>>> ''.join([random.choice(x) for i in range(8)])
'!%^[01y$'
  • 在Python中,字符串属于不可变对象,不支持原地修改,如果需要修改其中的值,只能重新创建一个新的字符串对象。然而,如果确实需要一个支持原地修改的unicode数据对象,可以使用io.StringIO对象或array模块。
>>> import io
>>> s = "Hello,world"
>>> sio = io.StringIO(s)
>>> sio.getvalue()
'Hello,world'
>>> sio.seek(7)
7
>>> sio.write("there!")
6
>>> sio.getvalue()
'Hello,wthere!'
>>> import array
>>> a = array.array('u',s)      #分类位置,分类对象
>>> print(a)
array('u', 'Hello,world')
>>> a[0] = 'y'
>>> a.tounicode()
'yello,world'
  • 例 4-1 编写桉树实现字符串加密和解密,循环使用指定密钥,采用简单的异或算法。异或再异或即可还原。
>>> def crypt(source,key):      #密匙,密钥
...     from itertools import cycle
...     result = ''
...     temp = cycle(key)
...     for ch in source:
...             result = result + chr(ord(ch)^ord(next(temp)))
...     return result
...
>>> source = 'Shandong Institute of Business and Technology'
>>> key = 'He Zhibin'
>>>
>>> print('Before Encrypted:'+source)
Before Encrypted:Shandong Institute of Business and Technology
>>> encrypted = crypt(source,key)
>>> print('After Encrypted:'+encrypted)
A4NS.h
*  -Sz     I:-H4
>>> decrypted = crypt(encrypted,key)
>>> print('After Decrypted:'+decrypted)
After Decrypted:Shandong Institute of Business and Technology
  • 例 4-3 检查并判断密码字符串的安全强度。
import string

def check(pwd):
    #密码必须至少包含6个字符
    if not isinstance(pwd,str) or len(pwd)<6:
        return 'not suitable for password'
    #密码强度等级与包含字符种类的对应关系
    d = {1:'weak',2:'below middle',3:'above middle',4:'strong'}
    #分别用来标记pwd是否含有数字、小写字母、大写字母和指定的标点符号
    r = [False]*4
    for ch in pwd:
        #是否包含数字
        if not r[0] and ch in string.digits:
            r[0] = True
        #是否包含小写字母
        elif not r[1] and ch in string.ascii_lowercase:
            r[1] = True
        #是否包含大写字母
        elif not r[2] and ch in string.ascii_uppercase:
            r[2] = True
        #是否包含指定的标点符号
        elif not r[3] and ch in ',.!;?<>':
            r[3] = True
    #统计包含的字符种类,返回密码强度
    return d.get(r.count(True),'error')

print(check('a2Cd,'))
posted @ 2019-08-14 20:27  旅人_Eric  阅读(181)  评论(0编辑  收藏  举报