Python内建函数——(一)

从官方文档整理总结,文档传送门:python doc


Python内建函数,共69个。

abs(x)

返回一个数的绝对值。参数x可以是整数或者浮点数,如果参数是复数,则返回这个复数的幅值。

integer1 = -5
float1 = -1.567
complexNum1 = -123 - 456j
print("abs(integer1):", abs(integer1))
print("abs(float1):", abs(float1))
print("abs(complexNum1):", abs(complexNum1))
all(iterable)

参数iterable表示一个可迭代变量,如果iterable的任意一个元素都是都是true或者iterable为空都会返回True。否则返回False。
当传入的参数为不可迭代对象时,会引发TypeError异常。
判断为空的值有,'',None,0

iterable1 = [1, 2, 3]
iterable2 = []
iterable3 = ['', None, 0]
print("all(iterable1):", all(iterable1))
print("all(iterable2):", all(iterable2))
print("all(iterable3):", all(iterable3))
# print("all(number):", all(5))
any(iterable)

如果iterable中只要有一个元素为true就返回True,否则返回False。
如果iterable为空,就返回False。

iterable4 = [4, 5, 6]
iterable5 = ['', 3]
iterable6 = ['', None, 0]
iterable7 = []
print("any(iterable4):", any(iterable4))
print("any(iterable5):", any(iterable5))
print("any(iterable6):", any(iterable6))
print("any(iterable7):", any(iterable7))
ascii(object)

如同repr(), 返回一个可以表示对象的可打印字符串,但是应该避免非ASCII字符串。
使用\x,\u,\U来避免非ASCII字符。
当object参数为一个非ascii字符的时候会引发UnicodeEncodeError异常。

print("a:", ascii('a'))
# print("中:", ascii('中'))
bin(x)

x必须是整数,将x转化为已‘0b’开头的二进制字符串
如果x不是整数,会引发TypeError异常。

x1 = 5
x2 = 6.66
print("binary of x1:", bin(x1))
# print("binary of x2:", bin(x2))

如果想要得到二进制,不论是否以‘0b’开头,有如下两种方式。

print(format(14, '#b'), format(14, 'b'))
print(f'{14: #b}', f'{14: b}')  # Python3.6特性
class bool([x])

返回Boolean值,也就是说,True或False其中一个。
如果x为false或者缺省,返回False。
bool类是int类的子类,并且无法再被继承。

print("bool(string):", bool('1'))
print("bool(int):", bool(1))
print("bool(None):", bool(None))
breakpoint(*args, **kws)

这是python3.7新增函数。文档大概说,调用了sys模块的breakpointhook()函数,进入debug模式。没怎么看懂。

class bytearray([source [,encoding [,errors]]])

返回一个新的字节数组,bytearray类是一个可变的整数序列(0 <= x < 256)
不传参数

new_bytearray = bytearray()
print("new_bytearray:", new_bytearray)

只传source
当source为int时,1输出\x00,2输出\x00\x00,依此类推。

new_bytearray2 = bytearray(10)
print("new_bytearray2:", new_bytearray2)

当source为float时,引发TypeError异常。

# new_bytearray3 = bytearray(1.55)
# print("new_bytearray3:", new_bytearray3)

当source为list时,输出每个元素的16进制,比如[4,5,6],输出bytearray(b'\x04\x05\x06')
list不能嵌套,比如[4, 5, 6, [1, 2, 3]]

new_bytearray4 = bytearray([4, 5, 6])
print("new_bytearray4:", new_bytearray4)

当source为字符串时,必须指定encoing。否则会报错TypeError:string argument without an encoding

new_bytearray5 = bytearray("I'm a string", encoding="utf-8")
print("new_bytearray5:", new_bytearray5)

source的参数如果是一个可迭代对象,那么这个迭代对象中的元素必须大于0,小于256。

class bytes([source [,ecoding [,errors]]])

返回一个新的bytes对象,这个对象是一个0<=x<256的不可迭代序列。

new_bytes_obj = bytes("123", encoding="utf-8", errors="出错了")
print("new_bytes_obj:", new_bytes_obj)
callable(object)

查看一个对象是否能被调用,这个对象指方法对象。
def method1():
pass
print(callable(method1))

你可能感兴趣的:(Python内建函数——(一))