一、数字和字符串
>>> ord('a') # ascii码 97 >>> chr(97) 'a' >>> >>> hex(16) # 16进制数 '0x10' >>> int('0x10', 16) 16 >>> >>> oct(16) # 8进制数 '0o20' >>> int('0o20', 8) 16 >>> >>> bin(16) # 2进制数 '0b10000' >>> int('0b10000', 2) 16
>>> >>> str(16) # 10进制数 '16' >>> int('16') 16 >>> str(5.5) # 浮点数 '5.5' >>> float('5.5') 5.5
二、字符串和bytes
>>> s = "美女,你好" >>> b = a.encode('utf-8') >>> b b'xe7xbex8exe5xa5xb3xefxbcx8cxe4xbdxa0xe5xa5xbd' >>> s_new = b.decode('utf-8') >>> s_new '美女,你好'
>>> s = "美女,你好" >>> b = bytes(s, 'utf-8') >>> b b'xe7xbex8exe5xa5xb3xefxbcx8cxe4xbdxa0xe5xa5xbd' >>> s_new = str(b, 'utf-8') >>> s_new '美女,你好'
三、bytes和bytearray
1 >>> b 2 b'xe7xbex8exe5xa5xb3xefxbcx8cxe4xbdxa0xe5xa5xbd' 3 >>> ba = bytearray(b) 4 >>> ba 5 bytearray(b'xe7xbex8exe5xa5xb3xefxbcx8cxe4xbdxa0xe5xa5xbd') 6 >>> b_new = bytes(ba) 7 >>> b_new 8 b'xe7xbex8exe5xa5xb3xefxbcx8cxe4xbdxa0xe5xa5xbd'
四、bytearray和字符串
1 >>> s = "世界,你好" 2 >>> ba = bytearray(s, 'utf-8') 3 >>> ba 4 bytearray(b'xe4xb8x96xe7x95x8cxefxbcx8cxe4xbdxa0xe5xa5xbd') 5 >>> s_new = str(ba, 'utf-8') 6 >>> s_new 7 '世界,你好'