python 类型转换总结

一、数字和字符串

>>> 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'\xe7\xbe\x8e\xe5\xa5\xb3\xef\xbc\x8c\xe4\xbd\xa0\xe5\xa5\xbd'
>>> s_new = b.decode('utf-8')
>>> s_new
'美女,你好'
>>> s = "美女,你好"
>>> b = bytes(s, 'utf-8')
>>> b
b'\xe7\xbe\x8e\xe5\xa5\xb3\xef\xbc\x8c\xe4\xbd\xa0\xe5\xa5\xbd'
>>> s_new = str(b, 'utf-8')
>>> s_new
'美女,你好'

三、bytes和bytearray

1 >>> b
2 b'\xe7\xbe\x8e\xe5\xa5\xb3\xef\xbc\x8c\xe4\xbd\xa0\xe5\xa5\xbd'
3 >>> ba = bytearray(b)
4 >>> ba
5 bytearray(b'\xe7\xbe\x8e\xe5\xa5\xb3\xef\xbc\x8c\xe4\xbd\xa0\xe5\xa5\xbd')
6 >>> b_new = bytes(ba)
7 >>> b_new
8 b'\xe7\xbe\x8e\xe5\xa5\xb3\xef\xbc\x8c\xe4\xbd\xa0\xe5\xa5\xbd'

四、bytearray和字符串

1 >>> s = "世界,你好"
2 >>> ba = bytearray(s, 'utf-8')
3 >>> ba
4 bytearray(b'\xe4\xb8\x96\xe7\x95\x8c\xef\xbc\x8c\xe4\xbd\xa0\xe5\xa5\xbd')
5 >>> s_new = str(ba, 'utf-8')
6 >>> s_new
7 '世界,你好'

 

posted @ 2017-12-21 15:50  魂~  阅读(505)  评论(0编辑  收藏  举报