Python内置函数定义为其函数已在Python中预定义的函数。 python解释器具有多个始终存在的函数供使用。这些函数称为内置函数。以下列出了Python中的一些内置函数:
python abs()函数用于返回数字的绝对值。它仅接受一个参数,即要返回其绝对值的数字。参数可以是整数和浮点数。如果参数是复数,则abs()返回其大小。
# integer number integer = -20 print('Absolute value of -40 is:', abs(integer)) # floating number floating = -20.83 print('Absolute value of -40.83 is:', abs(floating))
输出:
Absolute value of -20 is: 20 Absolute value of -20.83 is: 20.83
python all()函数接受可迭代的对象(例如列表,字典等)。如果传递的iterable中的所有项目均为true,则返回true。否则,它返回False。如果可迭代对象为空,则all()函数返回True。
# all values true k = [1, 3, 4, 6] print(all(k)) # all values false k = [0, False] print(all(k)) # one false value k = [1, 3, 7, 0] print(all(k)) # one true value k = [0, False, 5] print(all(k)) # empty iterable k = [] print(all(k))
输出:
True False False False True
python bin()函数用于返回指定整数的二进制表示形式。结果始终以前缀0b开头。
输出:
0b1010
python bool()使用标准真值测试过程将值转换为布尔值(True或False)。
test1 = [] print(test1,'is',bool(test1)) test1 = [0] print(test1,'is',bool(test1)) test1 = 0.0 print(test1,'is',bool(test1)) test1 = None print(test1,'is',bool(test1)) test1 = True print(test1,'is',bool(test1)) test1 = 'Easy string' print(test1,'is',bool(test1))
输出:
[] is False [0] is True 0.0 is False None is False True is True Easy string is True
Python中的python bytes()用于返回 bytes 对象。它是bytearray()函数的不可变版本。
它可以创建指定大小的空字节对象。
输出:
b ' Hello World.'
Python中的python callable()函数是可以调用的。如果传递的对象似乎是可调用的,则此内置函数检查并返回true,否则返回false。
输出:
False
python compile()函数将源代码作为输入并返回一个代码对象,该对象以后可以由exec()函数执行。
# compile string source to code code_str = 'x=5\ny=10\nprint("sum =",x+y)' code = compile(code_str, 'sum.py', 'exec') print(type(code)) exec(code) exec(x)
输出:
<class 'code'> sum = 15
python exec()函数用于动态执行Python程序,该程序可以是字符串或目标代码,并且可以接受大代码块,而eval()函数仅接受单个代码表达。
输出:
True 12
顾名思义,python sum()函数用于获取可迭代列表的数字总和。
输出:
7 17
如果iterable中的任何项目为true,则python any()函数将返回true。否则,它返回False。
l = [4, 3, 2, 0] print(any(l)) l = [0, False] print(any(l)) l = [0, False, 5] print(any(l)) l = [] print(any(l))
输出:
True False True False
python ascii()函数返回包含对象可打印表示形式的字符串,并使用\x,\u或\U转义符对字符串中的非ASCII字符进行转义。
normalText = 'Python is interesting' print(ascii(normalText)) otherText = 'Pyth?n is interesting' print(ascii(otherText)) print('Pyth\xf6n is interesting')
输出:
'Python is interesting' 'Pyth\xf6n is interesting' Pythön is interesting
python bytearray()返回一个bytearray对象,可以将这些对象转换为bytearray对象,或者创建指定大小的空bytearray对象。
string = "Python is a programming language." # string with encoding 'utf-8' arr = bytearray(string, 'utf-8') print(arr)
输出:
bytearray(b'Python is a programming language.')
python eval()函数解析传递给它的表达式,并在程序中运行python expression(code)。
输出:
9
python float()函数从数字或字符串中返回浮点数。
# for integers print(float(9)) # for floats print(float(8.19)) # for string floats print(float("-24.27")) # for string floats with whitespaces print(float(" -17.19\n")) # string float error print(float("xyz"))
输出:
9.0 8.19 -24.27 -17.19 ValueError: could not convert string to float: 'xyz'
python format()函数返回给定值的格式表示。
# d, f and b are a type # integer print(format(123, "d")) # float arguments print(format(123.4567898, "f")) # binary format print(format(12, "b"))
输出:
123 123.456790 1100
python frozenset()函数返回一个不变的Frozenset对象,该对象使用给定iterable中的元素初始化。
# tuple of letters letters = ('m', 'r', 'o', 't', 's') fSet = frozenset(letters) print('Frozen set is:', fSet) print('Empty frozen set is:', frozenset())
输出:
Frozen set is: frozenset({'o', 'm', 's', 'r', 't'}) Empty frozen set is: frozenset()
python getattr()函数返回对象的命名属性的值。如果找不到,它将返回默认值。
class Details: age = 22 name = "Phill" details = Details() print('The age is:', getattr(details, "age")) print('The age is:', details.age)
输出:
The age is: 22 The age is: 22
python globals()函数返回当前全局符号表的字典。
符号表定义为一种数据结构,其中包含有关程序的所有必要信息。它包括变量名,方法,类等。
输出:
The age is: 22
如果iterable中的任何项目为true,则python any()函数将返回true,否则返回False。
l = [4, 3, 2, 0] print(any(l)) l = [0, False] print(any(l)) l = [0, False, 5] print(any(l)) l = [] print(any(l))
输出:
True False True False
python iter()函数用于返回迭代器对象。它创建一个可以一次迭代一个元素的对象。
# list of numbers list = [1,2,3,4,5] listIter = iter(list) # prints '1' print(next(listIter)) # prints '2' print(next(listIter)) # prints '3' print(next(listIter)) # prints '4' print(next(listIter)) # prints '5' print(next(listIter))
输出:
1 2 3 4 5
python len()函数用于返回对象的长度。
输出:
6
python
# empty list print(list()) # string String = 'abcde' print(list(String)) # tuple Tuple = (1,2,3,4,5) print(list(Tuple)) # list List = [1,2,3,4,5] print(list(List))
输出:
[] ['a', 'b', 'c', 'd', 'e'] [1,2,3,4,5] [1,2,3,4,5]
python locals()方法更新并返回当前本地符号表的字典。
符号表定义为一种数据结构,其中包含有关程序的所有必要信息。它包括变量名,方法,类等。
def localsAbsent(): return locals() def localsPresent(): present = True return locals() print('localsNotPresent:', localsAbsent()) print('localsPresent:', localsPresent())
输出:
localsAbsent: {} localsPresent: {'present': True}
python map()函数用于在将给定函数应用于iterable的每个项目(列表,元组等)之后返回结果列表。
def calculateAddition(n): return n+n numbers = (1, 2, 3, 4) result = map(calculateAddition, numbers) print(result) # converting map object to set numbersAddition = set(result) print(numbersAddition)
输出:
<map object at 0x7fb04a6bec18> {8, 2, 4, 6}
python memoryview()函数返回给定参数的memoryview对象。
#A random bytearray randomByteArray = bytearray('ABC', 'utf-8') mv = memoryview(randomByteArray) # access the memory view's zeroth index print(mv[0]) # It create byte from memory view print(bytes(mv[0:2])) # It create list from memory view print(list(mv[0:3]))
输出:
65 b'AB' [65, 66, 67]
python object()返回一个空对象。它是所有类的基础,并拥有所有类默认的内置属性和方法。
输出:
<class 'object'> ['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
python open()函数打开文件并返回相应的文件对象。
# opens python.text file of the current directory f = open("python.txt") # specifying full path f = open("C:/Python33/README.txt")
输出:
Since the mode is omitted, the file is opened in 'r' mode; opens for reading.
Python chr()函数用于获取表示表示Unicode代码整数的字符的字符串。例如,chr(97)返回字符串" a"。该函数接受一个整数参数,如果超出指定范围,则抛出错误。参数的标准范围是0到1,114,111。
# 函数调用 result = chr(102) # It returns string representation of a char result2 = chr(112) # 显示结果 print(result) print(result2) # Verify, is it string type? print("is it string type:", type(result) is str)
输出:
ValueError: chr() arg not in range(0x110000)
Python complex()函数用于将数字或字符串转换为复数。此方法采用两个可选参数,并返回一个复数。第一个参数称为实部,第二个参数称为虚部。
# Python complex() function example # 函数调用 a = complex(1) # Passing single parameter b = complex(1,2) # Passing both parameters # 显示结果 print(a) print(b)
输出:
(1.5+0j) (1.5+2.2j)
Python delattr()函数用于从类中删除属性。它有两个参数,第一个是类的对象,第二个是无涯教程要删除的属性。删除属性后,该属性在类中不再可用,如果尝试使用类对象调用它,则会引发错误。
class Student: id = 101 name = "Pranshu" email = "pranshu@abc.com" # Declaring function def getinfo(self): print(self.id, self.name, self.email) s = Student() s.getinfo() delattr(Student,'course') # Removing attribute which is not available s.getinfo() # error: throws an error
输出:
101 Pranshu pranshu@abc.com AttributeError: course
Python dir()函数返回当前本地范围内的名称列表。如果在其上调用方法的对象具有名为__dir __()的方法,则将调用此方法,并且该方法必须返回属性列表。它采用单个对象类型参数。
输出:
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']
Python divmod()函数用于获取两个数字的余数和商。此函数接受两个数字参数并返回一个元组。这两个参数都是必需的并且是数字
输出:
(5, 0)
Python enumerate()函数返回一个枚举的对象。它有两个参数,第一个是元素序列,第二个是序列的起始索引。无涯教程可以通过循环或next()方法按顺序获取元素。
输出:
<enumerate object at 0x7ff641093d80> [(0, 1), (1, 2), (2, 3)]
Python dict()函数是用于创建字典的构造函数。 Python字典提供了三种不同的构造函数来创建字典:
# 函数调用 result = dict() # returns an empty dictionary result2 = dict(a=1,b=2) # 显示结果 print(result) print(result2)
输出:
{} {'a': 1, 'b': 2}
Python filter()函数用于获取过滤后的元素。此函数有两个参数,第一个是函数,第二个是可迭代的。过滤器函数返回可迭代对象的那些元素的序列,该对象为其返回 true值。
如果该函数不可用,则第一个参数可以为 none (无),并且仅返回 true 的元素。
# Python filter() function example def filterdata(x): if x>5: return x # 函数调用 result = filter(filterdata,(1,2,6)) # 显示结果 print(list(result))
输出:
[6]
Python hash()函数用于获取对象的哈希值。 Python使用哈希算法计算哈希值。哈希值是整数,用于在字典查找期间比较字典键。无涯教程只能对下面给出的类型进行哈希处理:
可哈希类型: * bool * int * long * float *string* Unicode * tuple *code对象。
# 函数调用 result = hash(21) # integer value result2 = hash(22.2) # decimal value # 显示结果 print(result) print(result2)
输出:
21 461168601842737174
Python help()函数用于获取与调用期间传递的对象相关的帮助。它带有一个可选参数,并返回帮助信息。如果未提供任何参数,则显示Python帮助控制台。它在内部调用python的帮助函数。
输出:
Welcome to Python 3.5's help utility!
Python min()函数用于从集合中获取最小的元素。此函数有两个参数,第一个是元素的集合,第二个是键,并返回集合中最小的元素。
# 函数调用 small = min(2225,325,2025) # returns smallest element small2 = min(1000.25,2025.35,5625.36,10052.50) # 显示结果 print(small) print(small2)
输出:
325 1000.25
在python中,集合是内置类,而此函数是此类的构造函数。它用于使用调用期间传递的元素来创建新集。它使用一个可迭代的对象作为参数,并返回一个新的set对象。
# 函数调用 result = set() # empty set result2 = set('12') result3 = set('learnfk') # 显示结果 print(result) print(result2) print(result3)
输出:
set() {'1', '2'} {'a', 'n', 'v', 't', 'j', 'p', 'i', 'o'}
Python hex()函数用于生成整数参数的十六进制值。它接受一个整数参数,并返回一个转换为十六进制字符串的整数。如果要获取浮点数的十六进制值,请使用float.hex()函数。
# 函数调用 result = hex(1) # integer value result2 = hex(342) # 显示结果 print(result) print(result2)
输出:
0x1 0x156
Python id()函数返回对象的身份。这是一个整数,保证是唯一的。此函数将参数作为对象,并返回表示身份的唯一整数。具有不重叠生存期的两个对象可能具有相同的id()值。
# 函数调用 val = id("Learnfk") # string object val2 = id(1200) # integer object val3 = id([25,336,95,236,92,3225]) # List object # 显示结果 print(val) print(val2) print(val3)
输出:
139963782059696 139963805666864 139963781994504
Python setattr()函数用于为对象的属性设置值。它需要三个参数,即一个对象,一个字符串和一个任意值,并且不返回任何参数。当无涯教程要向对象添加新属性并为其设置值时,这将很有帮助。
class Student: id = 0 name = "" def __init__(self, id, name): self.id = id self.name = name student = Student(102,"Sohan") print(student.id) print(student.name) #print(student.email) product error setattr(student, 'email','sohan@abc.com') # adding new attribute print(student.email)
输出:
102 Sohan sohan@abc.com
Python slice()函数用于从元素集合中获取元素的切片。 Python提供了两个重载的slice函数。第一个函数接受一个参数,而第二个函数接受三个参数并返回一个slice对象。该切片对象可用于获取集合的子部分。
# 函数调用 result = slice(5) # returns slice object result2 = slice(0,5,3) # returns slice object # 显示结果 print(result) print(result2)
输出:
slice(None, 5, None) slice(0, 5, 3)
Python sorted()函数用于对元素进行排序。默认情况下,它以升序对元素进行排序,但也可以降序对元素进行排序。它带有四个参数,并按排序顺序返回一个集合。对于字典,它仅对键排序,而不对值排序。
str = "learnfk" # declaring string # 函数调用 sorted1 = sorted(str) # sorting string # 显示结果 print(sorted1)
输出:
['a', 'a', 'i', 'j', 'n', 'o', 'p', 't', 't', 'v']
Python next()函数用于从集合中获取下一项。它接受两个参数,即迭代器和默认值,并返回一个元素。
此方法调用迭代器,如果不存在任何项目,则引发错误。为了避免错误,无涯教程可以设置一个默认值。
number = iter([256, 32, 82]) # Creating iterator # 函数调用 item = next(number) # 显示结果 print(item) # second item item = next(number) print(item) # third item item = next(number) print(item)
输出:
256 32 82
Python input()函数用于从用户获取输入。它提示用户输入并读取一行。读取数据后,它将数据转换为字符串并返回。如果读取EOF,则会引发错误 EOFError 。
输出:
Enter a value: 45 You entered: 45
Python int()函数用于获取整数值。它返回一个转换为整数的表达式。如果参数为浮点数,则转换将截断该数字。如果参数在整数范围之外,则它将数字转换为长型。
如果数字不是数字或给出底数,则数字必须是字符串。
# 函数调用 val = int(10) # integer value val2 = int(10.52) # float value val3 = int('10') # string value # 显示结果 print("integer values :",val, val2, val3)
输出:
integer values : 10 10 10
Python isinstance()函数用于检查给定的对象是否是该类的实例。如果对象属于该类,则返回true。否则返回False。如果该类是子类,则它也返回true。
isinstance()函数采用两个参数,即object和classinfo,然后返回True或False。
class Student: id = 101 name = "Learnfk" def __init__(self, id, name): self.id=id self.name=name student = Student(1010,"Learnfk") lst = [12,34,5,6,767] # 函数调用 print(isinstance(student, Student)) # isinstance of Student class print(isinstance(lst, Student))
输出:
True False
Python oct()函数用于获取整数的八进制值。此方法接受一个参数,并返回一个转换为八进制字符串的整数。如果参数类型不是整数,则抛出错误 TypeError 。
输出:
Octal value of 10: 0o12
python ord()函数返回一个整数,该整数表示给定Unicode字符的Unicode代码点。
# Code point of an integer print(ord('8')) # Code point of an alphabet print(ord('R')) # Code point of a character print(ord('&'))
输出:
56 82 38
python pow()函数用于计算数字的幂。它使x返回y的幂。如果给定第三个参数(z),则它将x返回到y模数z的幂,即(x,y)%z。
# positive x, positive y (x**y) print(pow(4, 2)) # negative x, positive y print(pow(-4, 2)) # positive x, negative y (x**-y) print(pow(4, -2)) # negative x, negative y print(pow(-4, -2))
输出:
16 16 0.0625 0.0625
python print()函数将给定对象打印到屏幕或其他标准输出设备上。
print("Python is programming language.") x = 7 # Two objects passed print("x =", x) y = x # Three objects passed print('x =', x, '= y')
输出:
Python is programming language. x = 7 x = 7 = y
python range()函数返回一个不可变的数字序列,默认情况下从0开始,递增1(默认),并以指定的数字结束。
# empty range print(list(range(0))) # using the range(stop) print(list(range(4))) # using the range(start, stop) print(list(range(1,7 )))
输出:
[] [0, 1, 2, 3] [1, 2, 3, 4, 5, 6]
python reversed()函数返回给定序列的反向迭代器。
# for string String = 'Java' print(list(reversed(String))) # for tuple Tuple = ('J', 'a', 'v', 'a') print(list(reversed(Tuple))) # for range Range = range(8, 12) print(list(reversed(Range))) # for list List = [1, 2, 7, 5] print(list(reversed(List)))
输出:
['a', 'v', 'a', 'J'] ['a', 'v', 'a', 'J'] [11, 10, 9, 8] [5, 7, 2, 1]
python round()函数四舍五入一个数字,并返回浮点数。
# for integers print(round(10)) # for floating point print(round(10.8)) # even choice print(round(6.6))
输出:
10 11 7
如果对象参数(第一个参数)是第二类(第二个参数)的子类,则python issubclass()函数将返回true。
class Rectangle: def __init__(rectangleType): print('Rectangle is a ', rectangleType) class Square(Rectangle): def __init__(self): Rectangle.__init__('square') print(issubclass(Square, Rectangle)) print(issubclass(Square, list)) print(issubclass(Square, (list, Rectangle))) print(issubclass(Rectangle, (list, Rectangle)))
输出:
True False True True
python str()将指定值转换为字符串。
输出:
'4'
python tuple()函数用于创建一个元组对象。
t1 = tuple() print('t1=', t1) # creating a tuple from a list t2 = tuple([1, 6, 9]) print('t2=', t2) # creating a tuple from a string t1 = tuple('Java') print('t1=',t1) # creating a tuple from a dictionary t1 = tuple({4: 'four', 5: 'five'}) print('t1=',t1)
输出:
t1= () t2= (1, 6, 9) t1= ('J', 'a', 'v', 'a') t1= (4, 5)
如果将单个参数传递给内置函数type(),则python type()返回指定对象的类型。如果传递了三个参数,则它将返回一个新的类型对象。
List = [4, 5] print(type(List)) Dict = {4: 'four', 5: 'five'} print(type(Dict)) class Python: a = 0 InstanceOfPython = Python() print(type(InstanceOfPython))
输出:
<class 'list'> <class 'dict'> <class '__main__.Python'>
python vars()函数返回给定对象的__dict__属性。
class Python: def __init__(self, x = 7, y = 9): self.x = x self.y = y InstanceOfPython = Python() print(vars(InstanceOfPython))
输出:
{'y': 9, 'x': 7}
python zip()函数返回一个zip对象,该对象映射多个集合的相似索引。它采用可迭代(可以为零或更多),使其成为一个迭代器,该迭代器根据传递的可迭代对象聚合元素,并返回一个元组的迭代器。
numList = [4,5, 6] strList = ['four', 'five', 'six'] # No iterables are passed result = zip() # Converting itertor to list resultList = list(result) print(resultList) # Two iterables are passed result = zip(numList, strList) # Converting itertor to set resultSet = set(result) print(resultSet)
输出:
[] {(5, 'five'), (4, 'four'), (6, 'six')}
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)