當(dāng)前位置:首頁(yè) > IT技術(shù) > 編程語(yǔ)言 > 正文

Python自動(dòng)化--4. python類型轉(zhuǎn)換
2022-04-18 10:50:58


4. 類型轉(zhuǎn)換

4.1 轉(zhuǎn)換為int

In [22]: int('10')
Out[22]: 10

In [23]: int('-10')
Out[23]: -10

In [24]: int (1.1)
Out[24]: 1

In [26]: int (1.5)
Out[26]: 1

4.2 轉(zhuǎn)換為float

In [27]: float(1)
Out[27]: 1.0

In [28]: float(-1)
Out[28]: -1.0

In [29]: float('1.1')
Out[29]: 1.1

4.3 轉(zhuǎn)換為str

In [30]: str(190)
Out[30]: '190'

In [31]: str(-9089)
Out[31]: '-9089'

In [32]: str(-000)
Out[32]: '0'

In [33]: str(-11.11)
Out[33]: '-11.11'

In [34]: str(b'hello', encoding='utf-8')
Out[34]: 'hello'

#二進(jìn)制轉(zhuǎn)換字符串時(shí),需指定字符編碼

4.4 轉(zhuǎn)換為二進(jìn)制

In [35]: bytes('小冬', encoding=('utf-8'))
Out[35]: b'xe5xb0x8fxe5x86xac'

#字符串轉(zhuǎn)換二進(jìn)制時(shí),需指定字符編碼

In [36]: b = bytes('小冬', encoding=('utf-8'))

In [37]: b
Out[37]: b'xe5xb0x8fxe5x86xac'

In [38]: str(b, encoding='utf-8')
Out[38]: '小冬'
In [41]: s = str(b, encoding='utf-8')

In [42]: s
Out[42]: '小冬'

In [43]: type(s)
Out[43]: str



本文摘自 :https://blog.51cto.com/v

開通會(huì)員,享受整站包年服務(wù)立即開通 >