Python3 类型转换

Python3 类型转换

String<==>Bytes

在 python 中字符串的编码和解码是转换的关键

1
2
3
4
5
6
7
8
9
10
11
>>> a='123456'
>>> a.encode('utf-8')
b'123456' #python3中bytes类型由b''区分
>>> b=a.encode('utf-8')
>>> b.decode('utf-8')
'123456'
>>> b[0]
49 #这里是1的ASCII编码值
>>> b[1]
50
>>>

String<==>Int

1
2
3
4
5
6
7
8
9
10
11
12
13
>>> a
'123456'
>>> a=123456
>>> b=str(a)
>>> b
'123456'
>>> c=int(b)
>>> c
123456
>>> a='010101' #01字符串也可以通过给定进制换成十进制数
>>> b=int(a,2)
>>> b
21

Bytes<==>Int

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
>>> a=b'010101'
>>> a
b'010101'
>>> int(a)
10101
>>> int(a,2) #通过给定的进制可以将该进制的bytes或字符串换成十进制
21
>>> int(a,8)
4161
>>> int(a,10)
10101
>>> b=10010
>>> c=str(b).encode('utf-8')
>>> c
b'10010'
>>> int(c)
10010
>>> a=9
>>> bin(a)#二进制
'0b1001'
>>> hex(a)#十六进制
'0x9'
>>> oct(a)#八进制
'0o11'
>>>

ASCII<==>String

1
2
3
4
5
6
7
8
9
10
>>> a='a'
>>> ord(a)
97
>>> b=ord(a)
>>> b
97
>>> c=chr(b)#chr可以把整数型通过ASCII和Unicode编码解码成字符
>>> c
'a'
>>>

Int<==>Unicode

1
2
3
4
5
6
7
8
9
10
11
12
>>> a='a'
>>> b=u'a'
>>> ord(b)
97
>>> a=97
>>> chr(a)
'a'
>>> ord('a')
97
>>> chr(2555)#unicode编码,unichr()方法在Python3中不可用。整合到了chr()中,可以直接通过unicode编码换成字符串
'৻' #2555是Unicode中的孟加拉语字符
>>>

List<==>String

1
2
3
4
5
6
7
8
9
10
11
12
>>> a=['a','b','c','d']
>>> b=''.join(a)
>>> b
'abcd'
>>> b=','.join(a)
>>>
>>> b
'a,b,c,d'
>>> c=b.split(',')
>>> c
['a', 'b', 'c', 'd']
>>>