什么是内置函数?
就是Python中已经写好了的函数,可以直接使用
内置函数图表:
以3.6.2为例
内置函数分类:
一、反射相关
二、基础数据类型相关
1.和数字相关
(1)数据类型
a.bool()
把一个值转换成布尔值
li = ['',[],1,12,0]for i inli:print(bool(i))#False#False#True#True#False
b.int()
把一个值转换成整型
num = input('Please input a number:')print(10 +int(num))#Please input a number:20#30
c.float()
把一个整数或数字字符串转换成带小数点的数
print(float('123.5'),type(float('123.5'))) #123.5
print(float(-50.2),type(float(-50.2))) #-50.2
d.complex()
返回一个复数
a = 1 + 2jb= 2
print(complex(a)) #(1+2j)
print(complex(b)) #(2+0j)
print(complex(2,3)) #(2+3j)
(2)进制转换
a.bin()
将一个数以二进制字符串的方式表示
print(bin(2)) #0b10
print(bin(10)) #0b1010
b.oct()
把一个数转换成八进制的字符串
print(oct(20),type(oct(20))) #0o24
print(oct(8),type(oct(8))) #0o10
c.hex()
把一个数字转换成十六进制的字符串
print(hex(10),type(hex(10))) #0xa
print(hex(28),type(hex(28))) #0x1c
(3)数学运算
a.abs()
对一个数的值取绝对值,结果不改变原值
a = -5
print(abs(a)) #5
b.divmod()
返回一个以商和余数组成的元祖
print(divmod(10,5),type(divmod(10,5))) #(2, 0)
print(divmod(4,9)) #(0, 4)
c.round()
将浮点值四舍五入
importmath
Pi=math.piprint(round(Pi,4)) #3.1416
d.pow()
一般情况下给函数两个数可以计算次方,若给定三个数则在幂运算后再取余
print(pow(2,3)) #8
print(pow(2,0.5)) #1.4142135623730951
print(pow(3,2,2)) #1
e.sum()
print(sum([2,2,3,5,6,2,4])) #24
print(sum([2,2,3,5,6,2,4],10)) #34 这里只是先让10进行sum的运算
f.min()
print(min(-1,-2,2,3)) #-2
print(min(-1,-2,2,3,key=abs)) #-1
print(min('aab','aaab','bc',key=len)) #bc
g.max()
print(max(-4,-2,2,3)) #3
print(max(-4,-2,2,3,key=abs)) #-4
print(max('aab','aaab','bc',key=len)) #aaab
2.和数据结构相关
(1)序列
<1>列表和元祖
a.list()
将一个元祖或者字符串转化成一个列表
print(list('abcdefg')) #['a', 'b', 'c', 'd', 'e', 'f', 'g']
print(list((1,2,'l'))) #[1, 2, 'l']
b.tuple()
将一个列表转化为元祖
print(tuple([1,2,3,'h','k'])) #(1, 2, 3, 'h', 'k')
<2>相关内置函数
a.reversed()
函数返回一个反转的迭代器
l = [1,2,3,'h','k',True]
l2= reversed(l) #
print(l2) #不改变原列表并返回一个迭代器
for i inl2:print(i)#True#k#h#3#2#1
b.slice()
l = ['a',1,2,3,4,8,'h','k']
sli= slice(2,7,2) #切片顾头不顾尾
print(l[sli]) #[2, 4, 'h']
<3>字符串
a.str()
将对象转化为适合人阅读的格式
tu = (1,2,'h')
dic= {'k1' : 1,'k2' : 2}
li= [1,2,3,'h']
i= 123
print(str(tu),type(tu)) #(1, 2, 'h')
print(str(dic),type(dic)) #{'k1': 1, 'k2': 2}
print(str(li),type(li)) #[1, 2, 3, 'h']
print(str(i),type(i)) #123
b.format()
主要用于格式化输出也可以用于数学方面的研究
value = 'ox123'tu= ('value1','value2','value3')print('get value->{0}'.format(value)) #get value->ox123
print('{0} {1} {2}'.format(*tu)) #value1 value2 value3
'''数字格式化'''a= 12.579
print('{:.2f}'.format(a)) #12.58 保留小数点的后两位
print('{:+.2f}'.format(a)) #+12.58 带符号的保留小数点的后两位
print('{:-.2f}'.format(-a)) #-12.58 带符号的保留小数点的后两位
print('{:.0f}'.format(a)) #13 不带小数返回并对结果四舍五入
print('{:.2%}'.format(a/100)) #12.58% 结果以百分比格式输出
b= 1001
print('{:0>8d}'.format(b)) #00001001 数字补0(填充左边宽度为8)
print('{:*>8d}'.format(b)) #****1001 数字补*(填充左边宽度为8)
print('{:*<8d}'.format(b)) #1001**** 数字补*(填充右边宽度为8)
c= 10**10
print('{:,}'.format(c)) #10,000,000,000 结果以逗号的形式分隔
print('{:.2e}'.format(c)) #1.00e+10 结果以指数标准格式输出
d= 7
print('{:>5d}'.format(d)) #7 向右对齐
print('{:<5d}'.format(d)) #7 向左对齐
print('{:^5d}'.format(d)) #7 中间对齐
e= 15
print('{:b}'.format(e)) #1111 返回二进制
print('{:d}'.format(e)) #15 返回十进制
print('{:o}'.format(e)) #17 返回八进制
print('{:x}'.format(e)) #f 返回十六进制
print('{:#x}'.format(e)) #0xf 返回带格式输出的十六进制小写
print('{:#X}'.format(e)) #0XF 返回带格式输出的十六进制大写
c.bytes()
主要用在网络编程、照片和视频、爬取网页等二进制文件的时候
print(bytes('Python爬虫',encoding='utf-8')) #b'Pythonxe7x88xacxe8x99xab'
d.bytearray()
返回一个bytes数组
b = bytes('Python爬虫',encoding='utf-8') #b'Pythonxe7x88xacxe8x99xab'
print(bytearray(b)) #bytearray(b'Pythonxe7x88xacxe8x99xab')
e.memoryview()
在一个缓冲区中查看一个对象,返回值为一个元祖
v = memoryview(bytearray('abcdef','utf-8'))print(v[2]) #99
print(v[-1]) #102
print(v[1:5:2]) #
print(v[1:5:2].tobytes()) #b'bd'
f.ord()
以一个字符作为参数返回一个unicode值或者ascii值,返回值为一个对应的十进制整数
print(ord('a')) #97
print(ord('A')) #65
print(ord('az')) #TypeError 超过给定长度报错
g.chr()
以一个十进制或十六进制的整数作为参数,数字范围为0-1114111(16进制为0x10FFFF),返回值为对应的ASCII字符
print(chr(65)) #A
print(chr(97)) #a
print(chr(0x35)) #5
h.ascii()
返回一个ascii字符,如果找不到这个ascii字符则通过repr()使用x,u或U编码的字符
print(ascii(10)) #10
print(ascii('a')) #'a'
print(ascii('中')) #'u4e2d'
i.repr()
将对象转化为供解释器读取的形式,返回一个string的格式
name = 'jane'
print('hello %r'%name) #hello 'jane'
print(repr('1')) #'1'
print(repr(1)) #1
(2)数据集合
<1>字典
a.dict()
<1>集合
a.set()
b.frozenset()
(3)相关内置函数
a.len()
b.enumerate()
c.all()
d.any()
e.zip()
f.filter()
g.map()
h.sorted()
三、作用域相关
1.locals()
找到当前作用域下所有的变量对应关系,并以字典返回
2.globals()
找到全局作用域下所有的变量对应关系,并以字典返回
a = 1b= 'hello'
deffunc():
c= 3
print(locals()) #{'c': 3}
print(globals()) #{'__name__': '__main__', '__loader__': <_frozen_importlib_external.sourcefileloader object at>,
#'func': , '__file__': 'C:/Users/Administrator/PycharmProjects/PYL/生成器/1.py',
#'__spec__': None, '__cached__': None, 'a': 1, '__builtins__': , 'b': 'hello',
#'__doc__': None, '__package__': None}
func()
四、面向对象相关
五、迭代器/生成器相关
1.range()
用于创建一个整数列表,常用在for循环中
li = list(range(0,11,2))print(li) #[0, 2, 4, 6, 8, 10]
2.__next__()
一个next对应一个值返回,如果这个迭代器已经没有值可以返回了那么就将报错
li = ['a',1,2]
iterator= li.__iter__()print(iterator.__next__()) #a
print(iterator.__next__()) #1
3.__iter__()
当一个具有可迭代数据使用__iter__()它会返回一个迭代器的内存地址
li = ['a',1,2]
iterator= li.__iter__()print(iterator) #
六、其他
1.输入输出
(1)input()
content = input('请输入一个数:')print(content)#请输入一个数:5#5
(2)print()
特殊字符分隔
print('a','b','c',sep = '&&',end = '') #a&&b&&c
将用户输入的数据直接写入文件
f = open('file',mode='w',encoding='utf-8')
content=input()print(content,sep=',',end='',file = f,flush=True) #file默认是输出到屏幕,如果设置文件句柄则输出到文件
#flush立即将内容输出到文件流,不留缓存
f.close()
2.内存相关
(1)hsah()
这里hash()中用到的参数必须是不可变数据类型,hash()完后结果会返回一串数字
print(hash(133)) #133
print(hash('aaaaa')) #-868214941
print(hash('aaaax')) #519685031
print(hash((1,2,3))) #-378539185
最直接的例子就是字典键的值,字典中的key是唯一的并且只能对应一个hash值
(2)id()
返回一个变量的内存地址
a = 5b= 'hello'c= [1,2]print(id(a)) #490310160
print(id(b)) #4872512
print(id(c)) #6656288
3.字符串类型代码的执行
(1)eval()
可以执行字符串类型的代码,有返回值,适用于简单计算
建议一般情况下不要使用eval()除非自己很明确要执行什么
print(eval('123')) #123
print(eval('1 + 2 + 3 + 4')) #10
(2)exec()
可以执行字符串类型的代码,无返回值,适用于简单流程控制
print(exec('123')) #None
print(exec('1 + 2 + 3 + 4 + 5')) #None
code = '''for i in [1,5,10]:
print(i*2)'''
exec(code)#2#10#20
(3)complie()
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
source:字符串或者AST
filename:代码文件的名称,如果不是从文件中读取代码则传递一些可辨认的值。当传入source参数时,filename参数传空即可
model:编译代码的种类 eval属于计算类、exec属于流程类、single属于交互类
计算类:
code = '2*5/10 + 6'ret= compile(code,'','eval')print(eval(ret)) #7.0
流程类:
code = '''print([i*i for i in range(10) if i > 5])'''ret= compile(code,'','exec')exec(ret) #[36, 49, 64, 81]
交互类:
code = "name = input('Please input your name:')"ret= compile(code,'','single')exec(ret)print(name)
4.文件操作相关
(1)open()
打开一个文件的相关操作
5.模块相关
(1)__import__()
#import time
time = __import__('time')print(time.time())
6.帮助
(1)help()
能够查看一个变量或类型的方法
help(bool)#Help on class bool in module builtins:# #class bool(int)#| bool(x) -> bool#|#| Returns True when the argument x is true, False otherwise.#| The builtins True and False are the only two instances of the class bool.#| The class bool is a subclass of the class int, and cannot be subclassed.#|#| Method resolution order:#| bool#| int#| object#|#| Methods defined here:#|#| __and__(self, value, /)#| Return self&value.#|#| __new__(*args, **kwargs) from builtins.type#| Create and return a new object. See help(type) for accurate signature.#|#| __or__(self, value, /)#| Return self|value.#|#| __rand__(self, value, /)#| Return value&self.#|#| __repr__(self, /)#| Return repr(self).#|#| __ror__(self, value, /)#| Return value|self.#|#| __rxor__(self, value, /)#| Return value^self.#|#| __str__(self, /)#| Return str(self).#|#| __xor__(self, value, /)#| Return self^value.#|#| ----------------------------------------------------------------------#| Methods inherited from int:#|#| __abs__(self, /)#| abs(self)#|#| __add__(self, value, /)#| Return self+value.#|#| __bool__(self, /)#| self != 0#|#| __ceil__(...)#| Ceiling of an Integral returns itself.#|#| __divmod__(self, value, /)#| Return divmod(self, value).#|#| __eq__(self, value, /)#| Return self==value.#|#| __float__(self, /)#| float(self)#|#| __floor__(...)#| Flooring an Integral returns itself.#|#| __floordiv__(self, value, /)#| Return self//value.#|#| __format__(...)#| default object formatter#|#| __ge__(self, value, /)#| Return self>=value.#|#| __getattribute__(self, name, /)#| Return getattr(self, name).#|#| __getnewargs__(...)#|#| __gt__(self, value, /)#| Return self>value.#|#| __hash__(self, /)#| Return hash(self).#|#| __index__(self, /)#| Return self converted to an integer, if self is suitable for use as an index into a list.#|#| __int__(self, /)#| int(self)#|#| __invert__(self, /)#| ~self#|#| __le__(self, value, /)#| Return self<=value.#|#| __lshift__(self, value, /)#| Return self<>self.#|#| __rshift__(self, value, /)#| Return self>>value.#|#| __rsub__(self, value, /)#| Return value-self.#|#| __rtruediv__(self, value, /)#| Return value/self.#|#| __sizeof__(...)#| Returns size in memory, in bytes#|#| __sub__(self, value, /)#| Return self-value.#|#| __truediv__(self, value, /)#| Return self/value.#|#| __trunc__(...)#| Truncating an Integral returns itself.#|#| bit_length(...)#| int.bit_length() -> int#|#| Number of bits necessary to represent self in binary.#| >>> bin(37)#| '0b100101'#| >>> (37).bit_length()#| 6#|#| conjugate(...)#| Returns self, the complex conjugate of any int.#|#| from_bytes(...) from builtins.type#| int.from_bytes(bytes, byteorder, *, signed=False) -> int#|#| Return the integer represented by the given array of bytes.#|#| The bytes argument must be a bytes-like object (e.g. bytes or bytearray).#|#| The byteorder argument determines the byte order used to represent the#| integer. If byteorder is 'big', the most significant byte is at the#| beginning of the byte array. If byteorder is 'little', the most#| significant byte is at the end of the byte array. To request the native#| byte order of the host system, use `sys.byteorder' as the byte order value.#|#| The signed keyword-only argument indicates whether two's complement is#| used to represent the integer.#|#| to_bytes(...)#| int.to_bytes(length, byteorder, *, signed=False) -> bytes#|#| Return an array of bytes representing an integer.#|#| The integer is represented using length bytes. An OverflowError is#| raised if the integer is not representable with the given number of#| bytes.#|#| The byteorder argument determines the byte order used to represent the#| integer. If byteorder is 'big', the most significant byte is at the#| beginning of the byte array. If byteorder is 'little', the most#| significant byte is at the end of the byte array. To request the native#| byte order of the host system, use `sys.byteorder' as the byte order value.#|#| The signed keyword-only argument determines whether two's complement is#| used to represent the integer. If signed is False and a negative integer#| is given, an OverflowError is raised.#|#| ----------------------------------------------------------------------#| Data descriptors inherited from int:#|#| denominator#| the denominator of a rational number in lowest terms#|#| imag#| the imaginary part of a complex number#|#| numerator#| the numerator of a rational number in lowest terms#|#| real#| the real part of a complex number
View Code
7.调用相关
(1)callable()
判断参数是否是一个可调用的函数名,若是则True,不是则False
a = 1
print(callable(a)) #False
deffunc():return 5
print(callable(func)) #True
print(callable(func())) #False
8.查看内置属性
(1)dir()
查看一个参数或变量的属性
print(dir([])) #['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
View Code
内容来源于网络如有侵权请私信删除