The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order.
Built-in Functions | ||||||
---|---|---|---|---|---|---|
abs() | dict() | help() | min() | setattr() | all() | dir() |
hex() | next() | slice() | any() | divmod() | id() | object() |
sorted() | ascii() | enumerate() | input() | oct() | staticmethod() | bin() |
eval() | int() | open() | str() | bool() | exec() | isinstance() |
ord() | sum() | bytearray() | filter() | issubclass() | pow() | super() |
bytes() | float() | iter() | print() | tuple() | callable() | format() |
len() | property() | type() | chr() | frozenset() | list() | range() |
vars() | classmethod() | getattr() | locals() | repr() | zip() | compile() |
globals() | map() | reversed() | import() | complex() | hasattr() | max() |
round() | delattr() | hash() | memoryview() | set() |
Official introduction: https://docs.python.org/3/library/functions.html
Detailed Interpretation of Built-in Functions
abs(x)
Returns the absolute value of the number, the parameter can be an integer or floating-point number, and the size if the parameter is a complex number.
# If the parameter is a complex number, its size is returned. >>> abs(-25) 25 >>> abs(25) 25
all(iterable)
all() loops through each element in parentheses, returning True if all elements in parentheses are true, or if iterable is empty, and False if one is false.
What I don't know in the process of learning can be added to me? python learning communication deduction qun, 784758214 There are good learning video tutorials, development tools and e-books in the group. Share with you the current talent needs of python enterprises and how to learn python from zero foundation, and what to learn >>> all([]) True >>> all([1,2,3]) True >>> all([1,2,""]) False # If one is false, all are false. >>> all([1,2,None]) False
False parameters are: False, 0, None, "",[], (), {} and so on. To check whether an element is false, bool can be used to view it.
any(iterable)
Cyclic elements, if one element is true, return True or False
>>> any([0,1]) True >>> any([0]) False
ascii(object)
Find the _repr_ method in the class of the object and get the return value
>>> class Foo: ... def __repr_(self): ... return "hello" ... >>> obj = Foo() >>> r = ascii(obj) >>> print(r) # Returns an iterative object <__main__.Foo object at 0x000001FDEE13D320>
bin(x)
Converting integer x to a binary string, if x is not an int type in Python, x must contain the method _index_() and return an integer value
# Returns an integer binary >>> bin(999) '0b1111100111'
# In non-integer cases, you must include the type of integer whose tangent return value of the _index_() method is integer >>> class myType: ... def __index__(self): ... return 35 ... >>> myvar = myType() >>> bin(myvar) '0b100011'
bool([x])
Look at the Boolean value of an element, either true or false
>>> bool(0) False >>> bool(1) True >>> bool([1]) True >>> bool([10]) True
bytearray([source [, encoding [, errors]]])
Returns a byte array, the Bytearray type is a variable sequence, and the range of elements in the sequence is [0, 255].
Sorce parameter:
- If the source is an integer, an initialized array with a length of source is returned.
- If source is a string, the string is converted to a byte sequence according to the specified encoding.
- If source is an iterative type, the element must be an integer in [0, 255].
- If source is an object consistent with the buffer interface, this object can also be used to initialize bytearray..
>>> bytearray(3) bytearray(b'\x00\x00\x00')
bytes([source[, encoding[, errors]]])
>>> bytes("asdasd",encoding="utf-8") b'asdasd'
callable(object)
Returns whether an object can be executed
>>> def func(): ... return 123 ... >>> callable(func) True >>> func = 123 >>> callable(func) False
chr(i)
Returns the corresponding character of a number in ASCII encoding, with a range of 256 values
>>> chr(66) 'B' >>> chr(5) '\x05' >>> chr(55) '7' >>> chr(255) '\xff' >>> chr(25) '\x19' >>> chr(65) 'A'
classmethod(function)
Class Method of Return Function
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
Compile strings into python executable code
>>> str = "for i in range(0,10): print(i)" >>> c = compile(str,'','exec') >>> exec(c) 0 1 2 3 4 5 6 7 8 9
complex([real[, imag]])
Create a complex value of real + imag * j or convert a string or number to a complex number. If the first parameter is a string, you do not need to specify the second parameter
>>> complex(1, 2) (1+2j) # number >>> complex(1) (1+0j) # Processing as a string >>> complex("1") (1+0j) # Note: This place should not have spaces on either side of the'+', that is, it can not be written as'+2j', it should be'+2j', otherwise it will be wrong. >>> complex("1+2j") (1+2j)
delattr(object, name)
Delete attribute values of objects
>>> class cls: ... @classmethod ... def echo(self): ... print('CLS') ... >>> cls.echo() CLS >>> delattr(cls, 'echo') >>> cls.echo() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: type object 'cls' has no attribute 'echo'
dict(**kwarg)
Create a dictionary with a data type
>>> dic = dict({"k1":"123","k2":"456"}) >>> dic {'k1': '123', 'k2': '456'}
dir([object])
Returns all methods in an object
>>> dir(str) ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce\_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
divmod(a, b)
Returns a//b (dividing integer) and the remainder of a to b, with the result type tuple
>>> divmod(10, 3) (3, 1)
enumerate(iterable, start=0)
Generate subscripts for elements
>>> li = ["a","b","c"] >>> for n,k in enumerate(li): ... print(n,k) ... 0 a 1 b 2 c
eval(expression, globals=None, locals=None)
Execute a string as an expression
>>> string = "1 + 3" >>> string '1 + 3' >>> eval(string) 4
exec(object[, globals[, locals]])
Execute strings as python code
>>> exec("for n in range(5): print(n)") 0 1 2 3 4
filter(function, iterable)
Filtering, looping iteratable objects, using the iterated objects as parameters of the function, returning True if it meets the criteria, or False if it does not.
>>> def func(x): ... if x == 11 or x == 22: ... return True ... >>> ret = filter(func,[11,22,33,44]) >>> for n in ret: ... print(n) ... 11 22
>>> list(filter((lambda x: x > 0),range(-5,5))) [1, 2, 3, 4]
float([x])
Converting integers and strings to floating-point numbers
>>> float("124") 124.0 >>> float("123.45") 123.45 >>> float("-123.34") -123.34
format(value[, format_spec])
String formatting
Detailed key: https://blog.ansheng.me/article/python-full-stack-way-string-formatting/
frozenset([iterable])
frozenset is a frozen set. It is immutable and has hash values. The advantage is that it can be used as a key in a dictionary or as an element in other collections. The disadvantage is that once created, it can't be changed. There is no add, remove method.
getattr(object, name[, default])
Returns the value of an object's named attribute, whose name must be a string. If the string is the name of one of the object's attributes, the result is the value of the attribute.
globals()
Gets or modifies global variables in the current file
>>> a = "12" >>> bsd = "54asd" >>> globals() {'__doc__': None, 'a': '12', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, 'bsd': '54asd', '__builtins__': <module 'builtins' (built-in)>, 'n': '__doc__', '__name__': '__main__', '__spec__': None, '__package__': None}
hasattr(object, name)
A parameter is an object and a string. If the string is the name of an attribute of the object, the result is True or False.
hash(object)
Returns the hash value of an object
>>> a = "asdadasdwqeq234sdfdf" >>> hash(a) 5390438057823015497
help([object])
View all the detailed methods of a class, or see the use details of a method
>>> help(list) Help on class list in module __builtin__: class list(object) | list() -> new empty list | list(iterable) -> new list initialized from iterable's items | | Methods defined here: | | __add__(...) | x.__add__(y) <==> x+y | | __contains__(...) | x.__contains__(y) <==> y in x | | __delitem__(...) | x.__delitem__(y) <==> del x[y] | | __delslice__(...) | x.__delslice__(i, j) <==> del x[i:j] | | Use of negative indices is not supported. ..........
hex(x)
Get the hexadecimal number of a number
>>> hex(13) '0xd'
id(object)
Returns the memory address of an object
>>> a = 123 >>> id(a) 1835400816
input([prompt])
interactive input
>>> name = input("Pless your name: ") Pless your name: ansheng >>> print(name) ansheng
int(x, base=10)
Get the decimal number of a number
>>> int("31") 31
It can also be used as a binary conversion
>>> int(10) 10 >>> int('0b11',base=2) 3 >>> int('11',base=8) 9 >>> int('0xe',base=16) 14
isinstance(object, classinfo)
Determine whether the object was created by this class
>>> li = [11,22,33] >>> isinstance(li,list) True
issubclass(class, classinfo)
See if an object is a subclass
iter(object[, sentinel])
Create an Iterable Object
>>> obj = iter([11,22,33,44]) >>> obj <list_iterator object at 0x000002477DB25198> >>> for n in obj: ... print(n) ... 11 22 33 44
len(s)
View the length of an object
>>> url="ansheng.me" >>> len(url) 10
list([iterable])
Create a list of data types
>>> li = list([11,22,33,44]) >>> li [11, 22, 33, 44]
locals()
Returns the local variables of the current scope and outputs them in dictionary form
>>> func() >>> def func(): ... name="ansheng" ... print(locals()) ... >>> func() {'name': 'ansheng'}
map(function, iterable, ...)
Each element in a sequence is passed to a function to execute and return
>>> list(map((lambda x : x +10),[1,2,3,4])) [11, 12, 13, 14]
max(iterable, *[, key, default])
max(arg1, arg2, *args[, key])
Take the maximum value in an object
>>> li = list([11,22,33,44]) >>> li = [11,22,33,44] >>> max(li) 44
memoryview(obj)
Return object obj's memory view object
>>> import struct >>> buf = struct.pack("i"*12, *list(range(12))) >>> x = memoryview(buf) >>> y = x.cast('i', shape=[2,2,3]) >>> print(y.tolist()) [[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]]
min(iterable, *[, key, default])
min(arg1, arg2, *args[, key])
Take the minimum of an object
>>> li = list([11,22,33,44]) >>> li = [11,22,33,44] >>> min(li) 11
next(iterator[, default])
Take only one element of an iteratable object at a time
>>> obj = iter([11,22,33,44]) >>> next(obj) 11 >>> next(obj) 22 >>> next(obj) 33 >>> next(obj) 44 >>> next(obj) # If there are no iterative elements, the error will be reported. Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
object
Returns a new feature-free object
oct(x)
Gets the octal of a string
>>> oct(13) '0o15'
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
A function for file operations.
# Open a file - >>> f = open("a.txt","r")
ord©
Converting a letter to a number in the ASCII counterpart table
>>> ord("a") 97 >>> ord("t") 116
pow(x, y[, z])
Returns the N-th power of a number
>>> pow(2, 10) 1024 >>> pow(2, 20) 1048576
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
Print Output
>>> print("hello word") hello word
property(fget=None, fset=None, fdel=None, doc=None)
range(start, stop[, step])
Generate a sequence
>>> range(10) range(0, 10) >>> for n in range(5): ... print(n) ... 0 1 2 3 4
repr(object)
Returns a printable representation of an object
>>> repr(111) '111' >>> repr(111.11) '111.11'
reversed(seq)
Inversion of an object's elements
>>> li = [1, 2, 3, 4] >>> reversed(li) <list_reverseiterator object at 0x000002CF0EF6A940> >>> for n in reversed(li): ... print(n) ... 4 3 2 1
round(number[, ndigits])
Rounding
>>> round(3.3) 3 >>> round(3.7) 4
set([iterable])
Create a data type as a collection
>>> varss = set([11,222,333]) >>> type(varss) <class 'set'>
setattr(object, name, value)
Setting an attribute for an object
slice(start, stop[, step])
The slicing of elements is the method invoked
sorted(iterable[, key][, reverse])
Sort the elements of an object
Code:
#!/usr/bin/env python # _*_ coding:utf-8 _*_ char=['Zhao',"123", "1", "25", "65","679999999999", "a","B","alex","c" ,"A", "_", "ᒲ",'a money','Grandchildren','plum',"more than", 'She',"Tuo", "A kind of", "iridium", "Poppy and clappery, clappery and clappery, clappery and clappery, clappery and clappery, clappery and clappery, clappery and clappery, clappery and clappery."] new_chat = sorted(char) print(new_chat) for i in new_chat: print(bytes(i, encoding='utf-8'))
Output results:
C:\Python35\python.exe F:/Python_code/Note/soretd.py ['1', '123', '25', '65', '679999999999', 'A', 'B', '_', 'a', 'alex', 'a money', 'c', 'ᒲ', 'A kind of', 'Tuo', 'She', 'more than', 'Grandchildren', 'plum', 'Zhao', 'Poppy and clappery, clappery and clappery, clappery and clappery, clappery and clappery, clappery and clappery, clappery and clappery, clappery and clappery.', 'iridium'] b'1' b'123' b'25' b'65' b'679999999999' b'A' b'B' b'_' b'a' b'alex' b'a\xe9\x92\xb1' b'c' b'\xe1\x92\xb2' b'\xe3\xbd\x99' b'\xe4\xbd\x97' b'\xe4\xbd\x98' b'\xe4\xbd\x99' b'\xe5\xad\x99' b'\xe6\x9d\x8e' b'\xe8\xb5\xb5' b'\xe9\x92\xb2\xe9\x92\xb2\xe3\xbd\x99\xe3\xbd\x99\xe3\xbd\x99' b'\xe9\x93\xb1' Process finished with exit code 0
staticmethod(function)
Static Method of Return Function
str(object=b'', encoding='utf-8', errors='strict')
Character string
>>> a = str(111) >>> type(a) <class 'str'>
sum(iterable[, start])
Summation
>>> sum([11,22,33]) 66
super([type[, object-or-type]])
Construction of Executing Parent Classes
tuple([iterable])
Create an object with a tuple data type
>>> tup = tuple([11,22,33,44]) >>> type(tup) <class 'tuple'>
type(object)
View the data type of an object
>>> a = 1 >>> type(a) <class 'int'> >>> a = "str" >>> type(a) <class 'str'>
vars([object])
See how many variables are in an object
zip(*iterables)
Converting the same sequence of two elements into a dictionary
>>> li1 = ["k1","k2","k3"] >>> li2 = ["a","b","c"] >>> d = dict(zip(li1,li2)) >>> d {'k1': 'a', 'k2': 'b', 'k3': 'c'}
import(name, globals=None, locals=None, fromlist=(), level=0)
Import module, using the imported module as an alias
Generate an example of random validation code
Generate a six-bit random validation code with random numbers and positions
# Import random module import random temp = "" for i in range(6): num = random.randrange(0,4) if num == 3 or num == 1: rad2 = random.randrange(0,10) temp = temp + str(rad2) else: rad1 = random.randrange(65,91) c1 = chr(rad1) temp = temp + c1 print(temp)
Output results
C:\Python35\python.exe F:/Python_code/sublime/Day06/built_in.py 72TD11
If you are still confused in the world of programming, you can join our Python learning button qun: 784758214 to see how our predecessors learned! Exchange experience! I am a senior Python development engineer, from basic Python script to web development, crawler, django, data mining and so on, zero-based to the actual project data have been collated. To every Python buddy! Share some learning methods and small details that need attention. Click to join us. python learner gathering place