以下全部基于py3.7测试
字符(串)/ascii值转换
chr()
- 参数范围为0~255,返回对应的字符
>>>chr(65)
‘A’
Unichr()
- 参数范围为0~65535(0x0000-0xFFFF),返回Unicode字符
- 在py3.x中已经归结到chr()里
>>> unichr(12345)
u’\u3039’
在py3直接显示出一个特护字符
ord()
- 以一个字符作为参数,返回对应的ASCII值
>>> ord('f')
102
bytes转字符串
- str()和.decode()两种
输入
b= b'\xe9\x80\x86\xe7\x81\xab'
print(str(b,'utf-8'))
print(b.decode())
print(b.decode('utf-8'))
c = b'\xe9\x80\x86\xe7\x81hhh\xab'
print(c.decode('utf-8','ignore')) # 忽略非法字 符,用strict会抛出异常
print(c.decode('utf-8','replace')) # 用?取代非法字符
d = b'^SdVkT#S ]`Y\\!^)\x8f\x80ism'
print(str(d,'gbk'))
输出
逆火
逆火
逆火
逆hhh
逆�hhh�
bytes转字符串
-bytes()和.encode()两种
str = '雅哈'
e = bytes(str,encoding='utf-8')
print(e)
f = str.encode('utf-8')
print(f)
输出
b’\xe9\x9b\x85\xe5\x93\x88’
b’\xe9\x9b\x85\xe5\x93\x88’
base64简单操作
- 库
import base64
其中有base16、base32、base64等多种加解码方式
- 加密解密之前、之后、过程中都应为bytes格式
import base64
strr = b'hello ya'
aa = base64.b64encode(strr)
print(aa)
bb = base64.b64decode(aa)
print(bb)
输出
b’aGVsbG8geWE=’
b’hello ya’