函數進階-10內置函數

內置函數

更多內置函數:https://docs.python.org/3/library/functions.html?highlight=built#asciihtml

經常使用.........

1.bytes()
解碼字符。python

res = '你好'.encode('utf8')
print(res)

b'\xe4\xbd\xa0\xe5\xa5\xbd'函數

res = bytes('你好', encoding='utf8')
print(res)

b'\xe4\xbd\xa0\xe5\xa5\xbd'
2.chr()/ord()ui

chr()參考ASCII碼錶將數字轉成對應字符;ord()將字符轉換成對應的數字。翻譯

print(chr(65))

Acode

print(ord('A'))

65
3.divmod()
分欄。htm

print(divmod(10, 3))

(3, 1)
4.enumerate()
帶有索引的迭代。對象

l = ['a', 'b', 'c']
for i in enumerate(l):
    print(i)

(0, 'a') (1, 'b') (2, 'c')
5.eval()
把字符串翻譯成數據類型。索引

lis = '[1,2,3]'
lis_eval = eval(lis)
print(lis_eval)

[1, 2, 3]ci

6.hash()
是否可哈希。

print(hash(1))

1

7.abs()
求絕對值。

print(abs(-13))  # 求絕對值

13

8.all()
可迭代對象內元素全爲真,則返回真。

print(all([1, 2, 3, 0]))
print(all([]))

False True

9.any()
可迭代對象中有一元素爲真,則爲真。

print(any([1, 2, 3, 0]))
print(any([]))

True False

10.bin()/oct()/hex()
二進制、八進制、十六進制轉換。

print(bin(17))
print(oct(17))
print(hex(17))

0b10001 0o21 0x11
11.dir()
列舉出全部time的功能。

import time
print(dir(time))

['_STRUCT_TM_ITEMS', 'doc', 'loader', 'name', 'package', 'spec', 'altzone', 'asctime', 'clock', 'ctime', 'daylight', 'get_clock_info', 'gmtime', 'localtime', 'mktime', 'monotonic', 'perf_counter', 'process_time', 'sleep', 'strftime', 'strptime', 'struct_time', 'time', 'timezone', 'tzname', 'tzset']
12.frozenset()
不可變集合。

s = frozenset({1, 2, 3})
print(s)

frozenset({1, 2, 3})
13.globals()/loacals()
查看全局名字;查看局部名字。

# print(globals())
def func():
    a = 1
#     print(globals())
    print(locals())

func()

{'a': 1}

14.pow()

print(pow(3, 2, 3))  # (3**2)%3

0

15.round()

print(round(3.5))

4

16.slice()

lis = ['a', 'b', 'c']
s = slice(1, 4, 1)
print(lis[s])  # print(lis[1:4:1])

['b', 'c']

17.sum()

print(sum(range(100)))

4950

12.__import__()
經過字符串導入模塊。

m = __import__('time')
print(m.time())

1556607502.334777

1.3面向對象知識點

classmethod staticmethod property delattr hasattr getattr setattr isinstance() issubclass() object() super()

相關文章
相關標籤/搜索