首页 > Python 笔记 > python提供的68个内置函数

python提供的68个内置函数

更新:
abs()函数

用来获得数值的绝对值。这个函数在你需要正值的时候非常有用。

x = -42
print(abs(x))  # 输出结果将为42
all()函数

你可以检查一个迭代器中的所有元素是否都返回True。如果有False,结果就是False。

my_list = [1, 2, 3, 4]
print(all(my_list))  # 由于列表中的所有元素都是真实的,因此输出结果是True。
any()函数

与all()相对应,检查迭代器中是否至少有一个元素是True。假如是False,结果就是False。

my_list = [0, False, 5]
print(any(my_list))  # 列表中的一个元素是5,因此输出结果是True。
ascii()函数

回到任何物体的可打印表示形式。尤其是,不是ASCII的字符将被转换。

str_object = 'pythön!'
print(ascii(str_object))  # “输出结果是”pyth\xf6n!'
bin()函数

将整个数字转换成前缀为“0b”的二进制字符串。

number = 7
print(bin(number))  # “0b1111”输出结果
bool()函数

转换值为布尔值。一般来说,False和True分别用于空值和非空值。

print(bool(0))     # False的输出结果是
print(bool(42))    # True的输出结果
bytearray()函数

回到一个新的字节数组,它是一个可变的序列,可以存储整数的字节范围。

bytearray_example = bytearray(5)
print(bytearray_example)  # bytearray的输出结果是(b\x00\x00\x00\x00')
bytes()函数

返回新的不可变字节序列,通常用于二进制数据操作。

bytes_example = bytes(5)
print(bytes_example)  # B'\x00\x00\x00\x00输出结果
callable()函数

用于检查对象是否可以调用,即是否可以使用括号运行对象。

def func(): 
    return "Hello World"

print(callable(func))  # 由于func是一个函数,因此输出结果是True
chr()函数

返回指定ASCII值对应的字符,常用于显示特定的ascii字符。

print(chr(97))  # “输出结果是”a'
print(chr(65))  # “输出结果是”A'
classmethod()函数

将方法声明为类方法,该方法可直接调用,无需实例化。

class MyClass:
    @classmethod
    def say_hello(cls):
        return f"Hello from {cls.__name__}"

print(MyClass.say_hello())  # “输出结果是”Hello from MyClass'
compile()函数

可以使用eval()和exec()来编译源字符串作为代码对象或AST对象。

code = 'x = 5\nprint("x =", x)'
compiled_code = compile(code, filename='<string>', mode='exec')
exec(compiled_code)
complex()函数

创建一个复数。

complex_number = complex(2, 3)
print(complex_number)  # “(2+3j)”输出结果

...(考虑到文章长度的限制,这里只展示一些内置函数的解释和示例)...

divmod()函数

将除数与余数一起返回,是一个元组。

print(divmod(9, 2))  # 输出结果为(4, 1)9除以2的结果是4余1。
enumerate()函数

回到索引和元素值,同时进行遍历集合。

for index, value in enumerate(['a', 'b', 'c']):
    print(f'Index: {index}, Value: {value}')
eval()函数

Python表达式在字符串中执行,并返回结果。

x = 1
print(eval('x + 1'))  # 输出结果为2
exec()函数

执行动态代码块,不返回值。

exec('print("Hello World")')  # Hello将被输出 World
filter()函数

在迭代器中使用函数筛选元素。

def is_positive(num):
    return num > 0

print(list(filter(is_positive, [-2, -1, 0, 1, 2])))  # 输出结果为[1, 2]
float()函数

用来将字符串和数字转换成浮点数。

print(float('10.5')  # 10.5的输出结果
print(float(20))      # 20.0的输出结果
format()函数

格式化值,结合字符串特别有用。

print(format(0.5, '%'))   # “50.00000”的输出结果
print(format(123, 'b'))   # “1111011”的输出结果, 表示为二进制

Python具有丰富的内置函数和强大的功能,从类型转换、数据聚合、复杂的数学计算和操作管理对象等,可以帮助我们在编程过程中执行各种常见的任务。熟练使用这些内置函数可以显著提高编程效率和可读性。

文章目录
顶部