1. 程式人生 > >基本資料型別-數字

基本資料型別-數字

int

將字串轉換為數字

#!/usr/bin/python
#-*-codeing: UTF-8-*-
num1 = 123
num2 = '123'
num3 = int(num2)
v1 = type(num1)
v2 = type(num2)
v3 = type(num3)
print(v1, v2, v3)
# <class 'int'> <class 'str'> <class 'int'>

int接收第二個引數表示被轉換的字串的進位制

#!/usr/bin/python
#-*-codeing: UTF-8-*-
num = '1010'
v1 = int(num, base=2)
v2 = int(num, base=10)
v3 = int(num, base=16)
print(v1, v2, v3)
# 10 1010 4112

bit_length

當前數字的二進位制表示的位數

#!/usr/bin/python
#-*-codeing: UTF-8-*-
# 1
a = 1
# 10
b = 2
# 11
c = 3
v1 = a.bit_length()
v2 = b.bit_length()
v3 = c.bit_length()
print(v1, v2, v3)
# 1 2 2