百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

Python 内置函数速查手册(函数大全,带示例)

itomcoil 2025-05-02 18:57 15 浏览

1. abs()

abs() 返回数字的绝对值。

>>> abs(-7)

输出: 7

>>> abs(7)

输出:

7

2. all()

all() 将容器作为参数。如果 python 可迭代对象中的所有值都是 True ,则此函数返回 True。空值为 False。

>>> all({'*','',''})

输出:

False

>>> all([' ',' ',' '])

输出:

True

3. any()

如果可迭代对象中的任意一个值为 True,则此函数返回 True。。

>>> any((1,0,0))

输出:

True

>>> any((0,0,0))

输出:

False

4. ascii()

返回一个表示对象的字符串。

>>> ascii('s')

输出:

“‘\u0219′”

>>> ascii('usor')

输出:

“‘u\u0219or'”

>>> ascii(['s','s'])

输出:

“[‘s’, ‘\u0219’]”

5. bin()

将整数转换为二进制字符串。不能将其应用于浮点数。

>>> bin(7)

输出:

‘0b111’

>>> bin(7.0)

输出:

Traceback (most recent call last):File “<pyshell#20>”, line 1, in <module>

bin(7.0)

TypeError: ‘float’ object cannot be interpreted as an integer

6. bool()

bool() 将值转换为布尔值。

>>> bool(0.5)

输出:

True

>>> bool('')

输出:

False

>>> bool(True)

输出:

True

7. bytearray()

bytearray() 返回给定大小的 python 新字节数组。

>>> a=bytearray(4)

>>> a

输出:

bytearray(b’\x00\x00\x00\x00′)

>>> a.append(1)

>>> a

输出:

bytearray(b’\x00\x00\x00\x00\x01′)

>>> a[0]=1

>>> a

输出:

bytearray(b’\x01\x00\x00\x00\x01′)

>>> a[0]

输出:

1

可以处理列表。

>>> bytearray([1,2,3,4])

输出:

bytearray(b’\x01\x02\x03\x04′)

8. bytes()

bytes()返回一个不可变的字节对象。

>>> bytes(5)

输出:

b’\x00\x00\x00\x00\x00′

>>> bytes([1,2,3,4,5])

输出:

b’\x01\x02\x03\x04\x05′

>>> bytes('hello','utf-8')

输出:

b’hello’Here, utf-8 is the encoding.

bytearray() 是可变的,而 bytes() 是不可变的。

>>> a=bytes([1,2,3,4,5])

>>> a

输出:

b’\x01\x02\x03\x04\x05′

>>> a[4]= 3

输出:

3Traceback (most recent call last):

File “<pyshell#46>”, line 1, in <module>

a[4]=3

TypeError: ‘bytes’ object does not support item assignment

Let’s try this on bytearray().

>>> a=bytearray([1,2,3,4,5])

>>> a

输出:

bytearray(b’\x01\x02\x03\x04\x05′)

>>> a[4]=3

>>> a

输出:

bytearray(b’\x01\x02\x03\x04\x03′)

9. callable()

callable() 用于检查一个对象是否是可调用的。

>>> callable([1,2,3])

输出:

False

>>> callable(callable)

输出:

True

>>> callable(False)

输出:

False

>>> callable(list)

输出:

True

10. chr()

chr() 用一个范围在(0~255)整数作参数(ASCII),返回一个对应的字符。

>>> chr(65)

输出:

‘A’

>>> chr(97)

输出:

‘a’

>>> chr(9)

输出:

‘\t’

>>> chr(48)

输出:

‘0’

11. classmethod()

classmethod() 返回函数的类方法。

>>> class hello:
    def sayhi(self):
        print("Hello World!")
        
>>> hello.sayhi=classmethod(hello.sayhi)
>>> hello.sayhi()

输出:

Hello World!

当我们将方法 sayhi() 作为参数传递给 classmethod() 时,它会将其转换为属于该类的 python 类方法。

然后,我们调用它,就像我们在 python 中调用静态方法一样。

12. compile()

compile() 将一个字符串编译为字节代码。

>>> exec(compile('a=5\nb=7\nprint(a+b)','','exec'))

输出:

12

13. complex()

complex() 创建转换为复数。

>>> complex(3)

输出:

(3+0j)

>>> complex(3.5)

输出:

(3.5+0j)

>>> complex(3+5j)

输出:

(3+5j)

14. delattr()

delattr() 用于删除类的属性。

>>> class fruit:
        size=7  
>>> orange=fruit()

>>> orange.size

输出:

7


>>> delattr(fruit,'size')

>>> orange.size

输出:

Traceback (most recent call last):File “<pyshell#95>”, line 1, in <module>

orange.size

AttributeError: ‘fruit’ object has no attribute ‘size’

15. dict()

dict() 用于创建一个字典。

>>> dict()

输出:

{}

>>> dict([(1,2),(3,4)])

输出:

{1: 2, 3: 4}

16. dir()

dir() 返回对象的属性。

>>> class fruit:
        size=7
        shape='round'
>>> orange=fruit()
>>> dir(orange)

输出:

[‘__class__’, ‘__delattr__’, ‘__dict__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__init_subclass__’, ‘__le__’, ‘__lt__’, ‘__module__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘__weakref__’, ‘shape’, ‘size’]

17. divmod()

divmod() 把除数和余数运算结果结合起来,返回一个包含商和余数的元组。

>>> divmod(3,7)

输出:

(0, 3)

>>> divmod(7,3)

输出:

(2, 1)

18. enumerate()

用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。

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

输出:

(0, ‘a’) (1, ‘b’) (2, ‘c’)

19. eval()

用来执行一个字符串表达式,并返回表达式的值。

字符串表达式可以包含变量、函数调用、运算符和其他 Python 语法元素。

>>> x=7

>>> eval('x+7')

输出:

14

>>> eval('x+(x%2)')

输出:

8

20. exec()

exec() 动态运行 Python 代码。

>>> exec('a=2;b=3;print(a+b)')

输出:

5

>>> exec(input("Enter your program"))

输出:

Enter your programprint

21. filter()

过滤掉条件为True的项目。

>>> list(filter(lambda x:x%2==0,[1,2,0,False]))

输出:

[2, 0, False]

22. float()

转换为浮点数。

>>> float(2)

输出:

2.0

>>> float('3')

输出:

3.0

>>> float('3s')

输出:

Traceback (most recent call last):File “<pyshell#136>”, line 1, in <module>

float(‘3s’)

ValueError: could not convert string to float: ‘3s’

>>> float(False)

输出:

0.0

>>> float(4.7)

输出:

4.7

23. format()

格式化输出字符串。

>>> a,b=2,3

>>> print("a={0} and b={1}".format(a,b))

输出:

a=2 and b=3

>>> print("a={a} and b={b}".format(a=3,b=4))

输出:

a=3 and b=4

24. frozenset()

frozenset() 返回一个冻结的集合,冻结后集合不能再添加或删除任何元素。

>>> frozenset((3,2,4))

输出:

frozenset({2, 3, 4})

25. getattr()

getattr() 返回对象属性的值。

>>> getattr(orange,'size')

输出:

7

26. globals()

以字典类型返回当前位置的全部全局变量。

>>> globals()

输出:

{‘__name__’: ‘__main__’, ‘__doc__’: None, ‘__package__’: None, ‘__loader__’: <class ‘_frozen_importlib.BuiltinImporter’>, ‘__spec__’: None, ‘__annotations__’: {}, ‘__builtins__’: <module ‘builtins’ (built-in)>, ‘fruit’: <class ‘__main__.fruit’>, ‘orange’: <__main__.fruit object at 0x05F937D0>, ‘a’: 2, ‘numbers’: [1, 2, 3], ‘i’: (2, 3), ‘x’: 7, ‘b’: 3}

27. hasattr()

用于判断对象是否包含对应的属性。

>>> hasattr(orange,'size')

输出:

True

>>> hasattr(orange,'shape')

输出:

True

>>> hasattr(orange,'color')

输出:

False

28. hash()

hash() 返回对象的哈希值。

>>> hash(orange)

输出:

6263677

>>> hash(orange)

输出:

6263677

>>> hash(True)

输出:

1

>>> hash(0)

输出:

0

>>> hash(3.7)

输出:

644245917

>>> hash(hash)

输出:

25553952

This was all about hash() Python In Built function

29. help()

获取有关任何模块、关键字、符号或主题的详细信息。

>>> help()

Welcome to Python 3.7's help utility!

If this is your first time using Python, you should definitely check out the tutorial on the Internet at https://docs.python.org/3.7/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing Python programs and using Python modules. To quit this help utility and return to the interpreter, just type "quit".

To get a list of available modules, keywords, symbols, or topics, type "modules", "keywords", "symbols", or "topics". Each module also comes with a one-line summary of what it does; to list the modules whose name or summary contain a given string such as "spam", type "modules spam".

help> map Help on class map in module builtins:

class map(object) | map(func, iterables) --> map object | | Make an iterator that computes the function using arguments from | each of the iterables. Stops when the shortest iterable is exhausted. | | Methods defined here: | | getattribute(self, name, /) | Return getattr(self, name). | | iter(self, /) | Implement iter(self). | | next(self, /) | Implement next(self). | | reduce(...) | Return state information for pickling. | | ---------------------------------------------------------------------- | Static methods defined here: | | new(args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature.

help>

30. hex()

Hex() 将整数转换为十六进制。

>>> hex(16)

输出:

‘0x10’

>>> hex(False)

输出:

‘0x0’

31. id()

id() 返回对象的标识。

>>> id(orange)

输出:

100218832

>>> id({1,2,3})==id({1,3,2})

输出:

True

32. input()

Input() 接受一个标准输入数据,返回为 string 类型。

>>> input("Enter a number")

输出:

Enter a number7 ‘7’

请注意,输入作为字符串返回。如果我们想把 7 作为整数,我们需要对它应用 int() 函数。

>>> int(input("Enter a number"))

输出:

Enter a number7

7

33. int()

int() 将值转换为整数。

>>> int('7')

输出:

7

34. isinstance()

如果对象的类型与参数二的类型相同则返回 True,否则返回 False。

>>> isinstance(0,str)

输出:

False

>>> isinstance(orange,fruit)

输出:

True

35. issubclass()

有两个参数 ,如果第一个类是第二个类的子类,则返回 True。否则,它将返回 False。

>>> issubclass(fruit,fruit)

输出:

True

>>> class fruit:`
        pass
>>> class citrus(fruit):
        pass
>>> issubclass(fruit,citrus)

输出:

False

36. iter()

Iter() 返回对象的 python 迭代器。

>>> for i in iter([1,2,3]):
          print(i)

输出:

1 2 3

37. len()

返回对象的长度。

>>> len({1,2,2,3})

输出:

3

38. list()

list() 从一系列值创建一个列表。

>>> list({1,3,2,2})

输出:

[1, 2, 3]

39. locals()

以字典类型返回当前位置的全部局部变量。

>>> locals()

输出:

{‘__name__’: ‘__main__’, ‘__doc__’: None, ‘__package__’: None, ‘__loader__’: <class ‘_frozen_importlib.BuiltinImporter’>, ‘__spec__’: None, ‘__annotations__’: {}, ‘__builtins__’: <module ‘builtins’ (built-in)>, ‘fruit’: <class ‘__main__.fruit’>, ‘orange’: <__main__.fruit object at 0x05F937D0>, ‘a’: 2, ‘numbers’: [1, 2, 3], ‘i’: 3, ‘x’: 7, ‘b’: 3, ‘citrus’: <class ‘__main__.citrus’>}

40. map()

会根据提供的函数对指定序列做映射。

>>> list(map(lambda x:x%2==0,[1,2,3,4,5]))

输出:

[False, True, False, True, False]

41. max()

返回最大值。

>>> max(2,3,4)

输出:

4

>>> max([3,5,4])

输出:

5

>>> max('hello','Hello')

输出:

‘hello’

42. memoryview()

memoryview() 返回给定参数的内存查看对象(memory view)。

>>> a=bytes(4)

>>> memoryview(a)

输出:

<memory at 0x05F9A988>

>>> for i in  memoryview(a): 
        print(i)

43. min()

min() 返回序列中的最小值。

>>> min(3,5,1)

输出:

1

>>> min(True,False)

输出:

False

44. next()

从迭代器返回下一个元素。

>>> myIterator=iter([1,2,3,4,5])

>>> next(myIterator)

输出:

1

>>> next(myIterator)

输出:

2

>>> next(myIterator)

输出:

3

>>> next(myIterator)

输出:

4

>>> next(myIterator)

输出:

5

遍历了所有项目后,再次调用 next() 时,会引发 StopIteration。

>>> next(myIterator)

输出:

Traceback (most recent call last):File “<pyshell#392>”, line 1, in <module>

next(myIterator)

StopIteration

45. object()

Object() 创建一个无特征的对象。

>>> o=object()

>>> type(o)

输出:

<class ‘object’>

>>> dir(o)

输出:

[‘__class__’, ‘__delattr__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__init_subclass__’, ‘__le__’, ‘__lt__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’]

46. oct()

oct() 将整数转换为其八进制表示形式。

>>> oct(7)

输出:

‘0o7’

>>> oct(8)

输出:

‘0o10’

>>> oct(True)

输出:

‘0o1’

47. open()

open() 打开一个文件。

>>> import os

>>> os.chdir('C:\\Users\\lifei\\Desktop')

# Now, we open the file ‘topics.txt’.

>>> f=open('topics.txt')

>>> f

输出:

<_io.TextIOWrapper name=’topics.txt’ mode=’r’ encoding=’cp1252′>

>>> type(f)

输出:

<class ‘_io.TextIOWrapper’>

48. ord()

是 chr() 函数或 unichr() 函数的配对函数,它以一个字符(长度为1的字符串)作为参数,返回对应的 ASCII 数值,或者 Unicode 数值

>>> ord('A')

输出:

65

>>> ord('9')

输出:

57

>>> chr(65)

输出:

‘A’

49. pow()

pow() 有两个参数。比如 x 和 y。它将值返回 x 的 y 次方。

>>> pow(3,4)

输出:

81

>>> pow(7,0)

输出:

1

>>> pow(7,-1)

输出:

0.14285714285714285

>>> pow(7,-2)

输出:

0.02040816326530612

50. print()

用于打印输出,最常见的一个函数。

>>> print("Hello world!")

输出:

Hello world!

51. property()

作用是在新式类中返回属性值。

class C(object):
    def __init__(self):
        self._x = None
    def getx(self):
        return self._x
    def setx(self, value):
        self._x = value
    def delx(self):
        del self._x
    x = property(getx, setx, delx, "I'm the 'x' property.")

52. range()

可创建一个整数列表,一般用在 for 循环中。

>>> for i in range(7,2,-2):
        print(i)

输出:

7 5 3

53. repr()

将对象转化为供解释器读取的形式。

>>> repr("Hello")

输出:

“‘Hello'”

>>> repr(7)

输出:

‘7’

>>> repr(False)

输出:

‘False’

54. reversed()

返回一个反转的迭代器。

>>> a=reversed([3,2,1])

>>> a

输出:

<list_reverseiterator object at 0x02E1A230>

>>> for i in a:
        print(i)

输出:

1 2 3

>>> type(a)

输出:

<class ‘list_reverseiterator’>

55. round()

将浮点数舍入到给定的位数。

>>> round(3.777,2)

输出:

3.78

>>> round(3.7,3)

输出:

3.7

>>> round(3.7,-1)

输出:

0.0

>>> round(377.77,-1)

输出:

380.0

56. set()

创建一个无序不重复元素集合。

>>> set([2,2,3,1])

输出:

{1, 2, 3}

57. setattr()

对应函数 getattr(),用于设置属性值,该属性不一定是存在的。

>>> orange.size

输出:

7

>>> orange.size=8

>>> orange.size

输出:

8

58. slice()

slice() 实现切片对象,主要用在切片操作函数里的参数传递。

>>> slice(2,7,2)

输出:

slice(2, 7, 2)

>>> 'Python'[slice(1,5,2)]

输出:

‘yh’

59. sorted()

对所有可迭代的对象进行排序操作。

>>> sorted('Python')

输出:

[‘P’, ‘h’, ‘n’, ‘o’, ‘t’, ‘y’]

>>> sorted([1,3,2])

输出:

[1, 2, 3]

60. staticmethod()

返回函数的静态方法。

>>> class fruit:
        def sayhi():
            print("Hi")
>>> fruit.sayhi=staticmethod(fruit.sayhi)
>>> fruit.sayhi()

输出:

Hi

>>> class fruit:
         @staticmethod
         def sayhi():
            print("Hi")
>>> fruit.sayhi()

输出:

Hi

61. str()

str() 返回一个对象的string格式。

>>> str('Hello')

输出:

‘Hello’

>>> str(7)

输出:

‘7’

>>> str(8.7)

输出:

‘8.7’

>>> str(False)

输出:

‘False’

>>> str([1,2,3])

输出:

‘[1, 2, 3]’

62. sum()

将可迭代对象作为参数,并返回所有值的总和。

>>> sum([3,4,5],3)

输出:

15

63. super()

super() 用于调用父类(超类)的一个方法。

>>> class person:
        def __init__(self):
            print("A person")
>>> class student(person):
        def __init__(self):
            super().__init__()
            print("A student")
>>> Avery=student()

输出:

A personA student

64. tuple()

创建一个元组。

输出:

(1, 3, 2)

>>> tuple({1:'a',2:'b'})

输出:

(1, 2)

65. type()

返回对象的类型。

>>> type({})

输出:

<class ‘dict’>

>>> type(set())

输出:

<class ‘set’>

>>> type(())

输出:

<class ‘tuple’>

>>> type((1))

输出:

<class ‘int’>

>>> type((1,))

输出:

<class ‘tuple’>

66. vars()

vars() 返回对象object的属性和属性值的字典对象。

>>> vars(fruit)

输出:

mappingproxy({‘__module__’: ‘__main__’, ‘size’: 7, ‘shape’: ’round’, ‘__dict__’: <attribute ‘__dict__’ of ‘fruit’ objects>, ‘__weakref__’: <attribute ‘__weakref__’ of ‘fruit’ objects>, ‘__doc__’: None})

67. zip()

zip() 用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。

>>> set(zip([1,2,3],['a','b','c']))

输出:

{(1, ‘a’), (3, ‘c’), (2, ‘b’)}

>>> set(zip([1,2],[3,4,5]))

输出:

{(1, 3), (2, 4)}

>>> a=zip([1,2,3],['a','b','c'])

>>> x,y,z=a

>>> x

输出:

(1, ‘a’)

>>> y

输出:

(2, ‘b’)

>>> z

输出:

(3, ‘c’)

相关推荐

selenium(WEB自动化工具)

定义解释Selenium是一个用于Web应用程序测试的工具。Selenium测试直接运行在浏览器中,就像真正的用户在操作一样。支持的浏览器包括IE(7,8,9,10,11),MozillaF...

开发利器丨如何使用ELK设计微服务中的日志收集方案?

【摘要】微服务各个组件的相关实践会涉及到工具,本文将会介绍微服务日常开发的一些利器,这些工具帮助我们构建更加健壮的微服务系统,并帮助排查解决微服务系统中的问题与性能瓶颈等。我们将重点介绍微服务架构中...

高并发系统设计:应对每秒数万QPS的架构策略

当面试官问及"如何应对每秒几万QPS(QueriesPerSecond)"时,大概率是想知道你对高并发系统设计的理解有多少。本文将深入探讨从基础设施到应用层面的解决方案。01、理解...

2025 年每个 JavaScript 开发者都应该了解的功能

大家好,很高兴又见面了,我是"高级前端进阶",由我带着大家一起关注前端前沿、深入前端底层技术,大家一起进步,也欢迎大家关注、点赞、收藏、转发。1.Iteratorhelpers开发者...

JavaScript Array 对象

Array对象Array对象用于在变量中存储多个值:varcars=["Saab","Volvo","BMW"];第一个数组元素的索引值为0,第二个索引值为1,以此类推。更多有...

Gemini 2.5编程全球霸榜,谷歌重回AI王座,神秘模型曝光,奥特曼迎战

刚刚,Gemini2.5Pro编程登顶,6美元性价比碾压Claude3.7Sonnet。不仅如此,谷歌还暗藏着更强的编程模型Dragontail,这次是要彻底翻盘了。谷歌,彻底打了一场漂亮的翻...

动力节点最新JavaScript教程(高级篇),深入学习JavaScript

JavaScript是一种运行在浏览器中的解释型编程语言,它的解释器被称为JavaScript引擎,是浏览器的一部分,JavaScript广泛用于浏览器客户端编程,通常JavaScript脚本是通过嵌...

一文看懂Kiro,其 Spec工作流秒杀Cursor,可移植至Claude Code

当Cursor的“即兴编程”开始拖累项目质量,AWS新晋IDEKiro以Spec工作流打出“先规范后编码”的系统工程思维:需求-设计-任务三件套一次生成,文档与代码同步落地,复杂项目不...

「晚安·好梦」努力只能及格,拼命才能优秀

欢迎光临,浏览之前点击上面的音乐放松一下心情吧!喜欢的话给小编一个关注呀!Effortscanonlypass,anddesperatelycanbeexcellent.努力只能及格...

JavaScript 中 some 与 every 方法的区别是什么?

大家好,很高兴又见面了,我是姜茶的编程笔记,我们一起学习前端相关领域技术,共同进步,也欢迎大家关注、点赞、收藏、转发,您的支持是我不断创作的动力在JavaScript中,Array.protot...

10个高效的Python爬虫框架,你用过几个?

小型爬虫需求,requests库+bs4库就能解决;大型爬虫数据,尤其涉及异步抓取、内容管理及后续扩展等功能时,就需要用到爬虫框架了。下面介绍了10个爬虫框架,大家可以学习使用!1.Scrapysc...

12个高效的Python爬虫框架,你用过几个?

实现爬虫技术的编程环境有很多种,Java、Python、C++等都可以用来爬虫。但很多人选择Python来写爬虫,为什么呢?因为Python确实很适合做爬虫,丰富的第三方库十分强大,简单几行代码便可实...

pip3 install pyspider报错问题解决

运行如下命令报错:>>>pip3installpyspider观察上面的报错问题,需要安装pycurl。是到这个网址:http://www.lfd.uci.edu/~gohlke...

PySpider框架的使用

PysiderPysider是一个国人用Python编写的、带有强大的WebUI的网络爬虫系统,它支持多种数据库、任务监控、项目管理、结果查看、URL去重等强大的功能。安装pip3inst...

「机器学习」神经网络的激活函数、并通过python实现激活函数

神经网络的激活函数、并通过python实现whatis激活函数感知机的网络结构如下:左图中,偏置b没有被画出来,如果要表示出b,可以像右图那样做。用数学式来表示感知机:上面这个数学式子可以被改写:...