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

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

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

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’)

相关推荐

PS小技巧 调整命令,让人物肤色变得更加白皙 #后期修图

我们来看一下如何去将人物的皮肤变得更加的白皙。·首先选中图层,Ctrl键加J键复制一层。·打开这里的属性面板,选择快速操作删除背景,这样就会将人物进行单独的抠取。·接下来在上方去添加一个黑白调整图层,...

把人物肤色提亮的方法和技巧

PS后期调白肤色提亮照片的方法。一白遮百丑,所以对于Photoshop后期来说把人物肤色调白是一项非常重要的任务。就拿这张素材图片来说,这张素材图片人脸的肤色主要偏红、偏黄,也不够白皙,该怎样对它进行...

《Photoshop教程》把美女图片调成清爽色彩及润肤技巧

关注PS精品教程,每天不断更新~~室内人物图片一般会偏暗,人物脸部、肤色及背景会出现一些杂点。处理之前需要认真的给人物磨皮及美白,然后再整体润色。最终效果原图一、用修补工具及图章工具简单去除大一点的黑...

PS后期对皮肤进行美白的技巧

PS后期进行皮肤美白的技巧。PS后期对皮肤进行美白的技巧:·打开素材图片之后直接复制原图。·接下来直接点击上方的图像,选择应用图像命令。·在通道这里直接选择红通道,混合这里直接选择柔光,然后点击确定。...

493 [PS调色]调模特通透肤色

效果对比:效果图吧:1、光位图:2、拍摄参数:·快门:160;光圈:8;ISO:1003、步骤分解图:用曲线调整图层调出基本色调。用可选颜色调整图层调整红色、黄色、白色和灰色4种颜色的混合比例。用色彩...

先选肤色再涂面部,卡戴珊的摄影师透露:为明星拍完照后怎么修图

据英国媒体12月17日报道,真人秀明星金·卡戴珊终于承认,她把女儿小北P进了家族的圣诞贺卡,怪不得粉丝们都表示这张贺卡照得非常失败。上周,这位39岁的女星遭到了一些粉丝针对这张照片的批评,她于当地时间...

如何在PS中运用曲线复制另一张照片的色调

怎样把另一张作品的外观感觉,套用到自己的照片上?单靠肉眼来猜,可能很不容易,而来自BenSecret的教学,关键是在PS使用了两个工具,让你可以准确比较两张照片的曝光、色调与饱和度,方便你调整及复制...

PS在LAB模式下调出水嫩肤色的美女

本PS教程主要使用Photoshop使用LAB模式调出水嫩肤色的美女,教程调色比较独特。作者比较注重图片高光部分的颜色,增加质感及肤色调红润等都是在高光区域完成。尤其在Lab模式下,用高光选区调色后图...

在Photoshop图像后期处理中如何将人物皮肤处理得白皙通透

我们在人像后期处理中,需要将人物皮肤处理的白皙通透,处理方法很多,大多数都喜欢使用曲线、磨皮等进行调整,可以达到亮但是不透,最终效果往往不是很好,今天就教大家一种如何将任务皮肤处理得白皙通透,希望能帮...

PS调色自学教程:宝宝照片快速调通透,简单实用!

PS调色自学教程:宝宝照片快速调通透。·首先复制图层,然后选择进入ACR滤镜,选择曲线锁定照片的亮部,也就高光位置,其他部位补亮一点,尤其是阴影的部位补亮多一些,让画面的层次均匀一点。·然后回到基本项...

【干货】如何利用PS进行人物美化

人物图像美化在Photoshop中非常常用,Photoshop作为一款功能强大的图像处理软件,不仅可以对人像进行基本的调色、美化和修复等处理,还可以改变人物的线条和幅度,如调整脸部器官和脸型的大小、调...

教大家一种可以快速把肤色处理均匀的方法@抖音短视频

快速把肤色处理均匀的方法。今天教大家一种可以快速把肤色处理均匀的方法。像这张照片整体肤色走紫红色,但是局部偏黄缘处理起来非常的麻烦。其实我们只需要新建空白图层,图层混合模式更改为颜色,再选择画笔工具把...

PS调色教程 利用RAW调出干净通透的肤色

要么不发,要么干货。后期教程来噜~用RAW调出干净通透的肤色。这次终于不会原片比PS后好看了吧。如果你依然这么觉得,请不要残忍的告诉我这个事实,泪谢TAT)附送拍摄花絮,感谢各位的支持更多风格请关注m...

photoshop后期皮肤变白的技巧

PS后期皮肤变白的技巧。1.PS后期让皮肤变白的方法有很多种,接下来教你一种非常简单容易上手的方法。2.打开素材图片之后,直接在小太极下拉框的位置添加一个纯色调整图层,颜色设置一个纯白色,点击...

Photoshop调出人物的淡雅粉嫩肤色教程

本教程主要使用Photoshop调出人物的淡雅粉嫩肤色教程,最终的效果非常的通透迷人,下面让我们一起来学习.出自:86ps效果图:原图:1、打开原图复制一层。2、用Topaz滤镜磨皮(点此下载)。3、...