用python最大的感觉就是方便,因为python中有很多API提供了非常方便的操作,能够实现一些常见的进制转换,编码转换以及字符串的大部分操作,这里记录一下。
In [4]: a = 10 In [5]: bin(a) # 转二进制 Out[5]: '0b1010' In [6]: oct(a) # 转八进制 Out[6]: '0o12' In [7]: hex(a) # 转十六进制 Out[7]: '0xa' In [8]: int(a) # 转十进制也用于取整 Out[8]: 10
In [17]: a = 97 In [18]: chr(a) # 转字符 Out[18]: 'a' In [19]: ord(chr(a)) # 转数字 Out[19]: 97
In [26]: import string In [27]: string.printable # 可打印字符 Out[27]: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c' In [28]: string.ascii_letters # 大小写字母 Out[28]: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' In [29]: string.ascii_lowercase # 小写字母 Out[29]: 'abcdefghijklmnopqrstuvwxyz' In [30]: string.ascii_uppercase # 大写字母 Out[30]: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
In [43]: import binascii In [44]: res = binascii.hexlify(b"fanxinli") # 字符串转十六进制 In [45]: res Out[45]: b'66616e78696e6c69' In [46]: binascii.unhexlify(res) # 十六进制转字符串 Out[46]: b'fanxinli'
In [50]: s = "fanxinli" In [51]: s.encode("ascii") # 单字节编码,编码范围[\x00-\x7f] Out[51]: b'fanxinli' In [52]: s.encode("gbk") # 国标,英文单字节,中文双字节 Out[52]: b'fanxinli' In [53]: s.encode("ISO-8859-1") # 单字节编码,编码范围[\x00-\xff] Out[53]: b'fanxinli' In [54]: s.encode("utf-8") # 变长编码,1-4字节,单字节编码兼容ascii,即范围为[\x00-\x7f] Out[54]: b'fanxinli'
In [67]: s = b"fanxinli" In [68]: s.decode("utf-8") # 解码为字符串类型 Out[68]: 'fanxinli' In [69]: str(s) # 直接str()会有点问题 Out[69]: "b'fanxinli'" In [70]: str(s, encoding="utf-8") # 带上编码 Out[70]: 'fanxinli' In [71]: bytes(s.decode("utf-8"), encoding="utf-8") # 同理也有bytes函数 Out[71]: b'fanxinli' # 转byte数组 In [95]: bytearray(b"fanxinli") Out[95]: bytearray(b'fanxinli') In [96]: bytearray(b"fanxinli")[0] Out[96]: 102 In [97]: chr(bytearray(b"fanxinli")[0]) Out[97]: 'f' # 十六进制字符串转byte数组 In [98]: s = "66616e78696e6c69" In [99]: bytearray.fromhex(s) Out[99]: bytearray(b'fanxinli') In [100]: bytearray.fromhex(s)[0] Out[100]: 102 In [101]: chr(bytearray.fromhex(s)[0]) Out[101]: 'f'
不忘初心,砥砺前行!