天天看點

python 内置函數

1. abs() # 求絕對值

abs(-10)
>>> 10
      

  

2. round() # 将一個浮點數四舍五入求一個最接近的整數

round(3.8)
>>> 4.0
round(3.2)
>>> 3.0
      

3. pow() # 求幂函數

pow(2,8)
>>> 256
pow(4,6)
4096
      

4. int() # 整數

int(10.4)
>>> 10
      

5. float() # 浮點數

float(12)
>>> 12.0
      

6. all(iterable) # iterable的所有元素不為0、''、False或者iterable為空,all(iterable)傳回True,否則傳回False

#注:0,[],(),{},"" 為False," " 不是False

# 等價于函數
def all (iterable): # iterable 可疊代對象
for element in iterable:
if not element:
return False
return True
#eg_v1
all(["a","b","c","d"])
>>> True
all(["a","b","c","d",""]) # 存在“”空元素
>>> False
all((0,1,2,3,4))
>>> False
all([])
>>> True
all(())
>>> True
      

7. any(iterable) # iterable的任何元素不為0、''、False,all(iterable)傳回True。如果iterable為空,傳回False

def any(iterable):
for element in iterable:
if element:
return False
return True

# eg_v1
any(["a","b","c","d"])
>>> True
any(["a","b","c","d",""])
>>> True
any([0,"",{},[],()])
>>> False
      

8. ascii() # 傳回一個可列印的對象字元串方式表示,如果是非ascii字元就會輸出\x,\u或\U等字元來表示。與python2版本裡的repr()是等效的函數。

9. bin() #将整數轉換為二進制字元串

注:0b 表示二進制,0x 表示十六進制

bin(12)
>>> '0b1100'
      

10. hex() # 将整數轉換為十六進制字元串

hex(15)
>>> '0xf'
      

11. oct() # 将整數轉換為八進制字元串

oct(254)
>>> '0376'
      

12. bool() # 将x轉換為Boolean類型,如果x預設,傳回False,bool也為int的子類

bool()
>>> False
bool(1)
>>> True
      

13. bytes()

# 傳回值為一個新的不可修改位元組數組,每個數字元素都必須在0 - 255範圍内,是bytearray函數的具有相同的行為,差别僅僅是傳回的位元組數組不可修改。

a = bytes(5)
print(a)
>>> b'\x00\x00\x00\x00\x00'

b = bytes("python","utf-8")
print(b)
# b'python'

c = bytes([1,2,3,4,5])
print (c)
>>> b'\x01\x02\x03\x04\x05'
      

14. bytearray() # bytearray([source [, encoding [, errors]]])傳回一個byte數組。Bytearray類型是一個可變的序列,并且序列中的元素的取值範圍為 [0 ,255]。

# 如果為整數,則傳回一個長度為source的初始化數組;

# 如果為字元串,則按照指定的encoding将字元串轉換為位元組序列;

# 如果為可疊代類型,則元素必須為[0 ,255]中的整數;

# 如果為與buffer接口一緻的對象,則此對象也可以被用于初始化bytearray.。

a = bytearray(3)
print (a)
>>> bytearray(b'\x00\x00\x00')

b = bytearray("python","utf-8")
print(b)
>>> bytearray(b'python')

c = bytearray([1,2,3,4,5])
print (c)
>>> bytearray(b'\x01\x02\x03\x04\x05')

d = bytearray(buffer("python")
print (d)
>>> bytearray(b'python')
      

15. bool(x) # 參數x:任意對象或預設;大家注意到:這裡使用了[x],說明x參數是可有可無的,如果不給任何參數則會傳回False。

a = bool(0)
>>> False
b = bool([])
print (b)
>>> False
c = bool({})
print (c)
>>> False
d = bool("bool")
print (d)
>>> True
      

16. chr(x) # 傳回整數x對應的ASCII字元。與ord()作用相反。

print (chr(97))
>>> a
print (chr(98))
>>> b
      

17. ocd(x) # 函數功能傳入一個Unicode 字元,傳回其對應的整數數值。

print (ord("a"))
>>> 97
print (ord("b"))
>>> 98
      

18. compile()