Python common built-in functions

Keywords: ascii encoding Spring Lambda

Built in function table

abs() all() any() ascii() bin()
bool() bytes() callable() compile() complex()
chr() delattr() dir() divmod() enumerate()
eval() exec() exit() filter() float()
frozenset() getattr() globals() hasattr() hash()
help() hex() id() input() int()
isinstance() iter() len() list() set()
tuple() dict() glocals() map() max()
min() next() oct() open() ord()
pow() print() quit() range() reduce()
repr() reversed() round() sorted() str()
sum() type() zip()

Specific usage and instructions

abs()
# Function prototype: abs(x)
# Function Description: returns the absolute value of a number. Arguments can be integers or floating-point numbers. If the argument is a complex number, return its module.
print(abs(-1)) # 1
print(abs(-1.34)) # 1.34
print(abs(3j)) # 3.0
all()
# Function prototype: all(iterable)
# Function Description: returns True if all elements of iterable are True (or the iterator is empty).
print(all([])) # True
print(all([1, 2, 3, 4])) # True
print(all([False, True])) # False
any()
# Function prototype: any(iterable)
# Function Description: returns True if any element of iterable is True. Returns False if the iterator is empty.
print(any([])) # False
print(any([1, 2, 3, 4])) # True
print(any([False, True])) # True
ascii()
# Function prototype: ascii(object)
# Function Description: returns the ASCII representation of the object. If necessary, use escape characters to represent specific characters.
class Temp(object):
    pass
temp = Temp()
print(ascii(temp)) # <__main__.Temp object at 0x01341B90>

bin()
# Function prototype: bin(x)
# Function Description: converts an integer into a binary string prefixed with "0b".
print(bin(23)) # 0b10111
bool()
# Function prototype: bool(x)
# Function Description: returns a Boolean value, True or False. 
class Temp(object):
    pass
temp = Temp()
print(bool(temp)) # True
print(bool(0)) # False
print(bool(1.0123)) # True
print(bool(1j)) # True
print(bool([])) # False
print(bool([1])) # True
bytes()
# Function prototype: bytes([source[, encoding[, errors]]])
# Function Description: generates a byte string, or converts the specified object x to a byte string representation.
print(bytes([1, 2, 3, 4]))
print(bytes('HelloWorld', 'ASCII'))
callable()
# Function prototype: callable(object)
# Function Description: test whether obj is callable. Classes and functions are callable, as are objects that contain classes of the \.
x = 123
# False
print(callable(x))

def func():
    pass
# True
print(callable(func))
chr()
# Function prototype: chr(i)
# Function Description: returns the string format of the character whose Unicode code point is the integer i.
# Chen
print(chr(38472))
compile()
# Function prototype: compile (source, filename, mode, flags = 0, don'u inherit = false, optimize = - 1)
# Function Description: compile source into code or AST object. Code objects can be executed by exec() or eval(). 
'''
0
1
2
3
4
5
6
7
8
9
'''
exec(compile('for i in range(10): print(i)', '', 'exec'))
complex()
# Function prototype: complex([real[, imag]])
# Function Description: returns a complex value of real + imag*1j, or converts a string or number to a complex value.
# 1 + 2j
print(complex(1,2))
# -1 + 1j
print(complex('-1+1j'))
delattr()
#Function prototype: delattr(object, name)
#Function Description: delete the properties of the specified object. Refer to setattr().
dict()
#Function prototype: any(iterable)
#Function Description: convert the iteratable object to a dictionary or generate an empty dictionary. Refer to list(), set(), or tuple().
dir()
# Function prototype: dir([object])
# Function Description: returns a list of names in the current local scope if there is no argument. If there is an argument, it attempts to return a list of valid properties for the object.
import keyword
# ['__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'iskeyword', 'kwlist', 'main']
print(dir(keyword))
divmod()
# Function prototype: divmod(a, b)
# Function Description: it takes two (non complex) numbers as arguments and returns a pair of quotient and remainder when integer division is performed. For mixed operand types, the rules for binocular arithmetic operators apply. For integers, the result is the same as (A / / B, a% B). For floating-point numbers, the result is (Q, a% B), q is usually math.floor(a / b), but may be smaller than 1. In any case, Q * B + a% B and a are basically equal; if a% B is non-zero, its symbol is the same as B, and 0 < = ABS (a% B) < ABS (b).
# (3, 1)
print(divmod(7,2))
enumerate()
# Function prototype: enumerate(iterable, start=0)
# Function Description: returns an enumeration object. 
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
# [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
print(list(enumerate(seasons)))
eval()
# Function prototype: eval(expression, globals=None, locals=None)
# Function Description: evaluates and returns the value of the expression in the string expression.
# 10
print(eval('1+2+3+4'))
exec()
# Function prototype: exec(object[, globals[, locals]])
# Function Description: execute code or code object x.
# HelloWorld
exec('print("HelloWorld")')
filter()
# Function prototype: filter(function, iterable)
# Function Description: returns the filter object, including those elements in the sequence seq that make the single parameter function func return True. If the function func is None, returns the filter object containing the element equivalent to True in SEQ.
def isOdd(num):
    return num % 2 == 1
# [1, 3, 5, 7, 9]
print(list(filter(isOdd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])))
float()
# Function prototype: float([x])
# Function Description: returns the floating-point number generated from a number or string x.
# 123.0
print(float(123))
# 123.456
print(float('123.456'))
frozenset()
# Function prototype: frozen ([Iterable])
# Function Description: returns a frozen collection. After freezing, the collection cannot add or delete any elements.
# frozenset({1, 2, 3, 4, 5, 6, 7, 8, 9})
print(frozenset(range(1, 10)))
getattr()
# Function prototype: getattr(object, name[, default])
# Function Description: returns the value of an object's named property. name must be a string. If the string is one of the properties of the object, the value of the property is returned.
class Temp:
    def __init__(self):
        self.var = 1
obj = Temp()
# 1
print(getattr(obj, 'var'))
globals()
#Function prototype: globals()
#Function Description: returns a dictionary representing the current global symbol table. This is always the dictionary of the current module (in a function or method, not the module that calls it, but the module that defines it). Other reference locales().
hasattr()
# Function prototype: hasattr(object, name)
# Function Description: returns True if the string is the name of one of the object's properties, False otherwise. (this function is implemented by calling getattr(object, name) to see if there is an AttributeError exception.)
class Temp:
    def __init__(self):
        self.var = 1
obj = Temp()
# True
print(hasattr(obj, 'var'))
hash()
# Function prototype: hash(object)
# Function Description: returns the hash value of the object, if any. The hash value is an integer. They are used to quickly compare dictionary keys when looking up elements in a dictionary. Numeric variables of the same size have the same hash value (even if they are of different types, such as 1 and 1.0).
x = 1
# 1
print(hash(x))
y = 1.0
# 1
print(hash(y))
help()
# Function prototype: help([object])
# Function Description: start the built-in help system (this function is mainly used in interactive). If there are no arguments, the interactive help system will be launched in the interpreter console. If the argument is a string, search for the string in the module, function, class, method, keyword, or document topic and print help information on the console. If the argument is any other object, a help page is generated for that object.
from functools import reduce
'''Help on built-in function reduce in module _functools:

reduce(...)
    reduce(function, sequence[, initial]) -> value
    
    Apply a function of two arguments cumulatively to the items of a sequence,
    from left to right, so as to reduce the sequence to a single value.
    For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
    ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items
    of the sequence in the calculation, and serves as a default when the
    sequence is empty.'''
help(reduce)
hex()
# Function prototype: hex(x)
# Function Description: converts an integer to a lowercase hexadecimal string prefixed with "0x".
# 0xff
print(hex(255))
id()
# Function prototype: id(object)
# Function Description: returns the identification value of the object. The value is an integer that is guaranteed to be unique and constant throughout the life of the object. Two objects with non overlapping lifetimes may have the same id() value. This returns the memory address of the object.
# 1493970064
x = 1
print(id(x))
input()
#Function prototype: input([prompt])
#Function Description: basic input function, return string.
int()
# Function prototype: int(x, base=10)
# Function Description: returns the integer part of the real number (float), Fraction or high-precision real number (Decimal) x, or converts the base string x to Decimal and returns it. d defaults to Decimal.
# 1234
print(int(1234.56789))
# Convert '101' of binary to decimal and return 5
print(int('101', 2))
isinstance()
# Function prototype: isinstance(object, classinfo)
# Function Description: judge whether an object is a known type.
# True
print(isinstance(1, int))
iter()
# Function prototype: iter(object[, sentinel])
# Function Description: returns an iterator object.
# <class 'list_iterator'>
print(type(iter([1, 2, 3])))
len()
# Function prototype: len(s)
# Function Description: returns the length of the object (number of elements). Arguments can be sequences (such as string, bytes, tuple, list, range, etc.) or collections (such as dictionary, set, or frozen set, etc.).
# 3
print(len([1, 2, 3]))
list()
# Function prototype: list([iterable])
# Function Description: convert iteratable objects to lists or generate empty lists.
# []
print(list())
# [1, 2, 3]
print(list((1, 2, 3)))
locals()
# Function prototype: locals()
# Function Description: returns all local variables of the current location with dictionary type.
def func(args):
    tag = 123456
    print(locals())
# {'tag': 123456, 'args': 789}
func(789)
map()
# Function prototype: map(function, iterable,...)
# Function Description: returns an iterator that applies function to each item in iterable and outputs its result. If an additional iterable parameter is passed in, the function must accept the same number of arguments and be applied to items obtained in parallel from all iteratable objects. When there are multiple iteratable objects, the whole iteration will end when the shortest one is exhausted.
from random import randint

number = randint(1, 1e30)
# 660863965300849176946136467008
print(number)
# [6, 6, 0, 8, 6, 3, 9, 6, 5, 3, 0, 0, 8, 4, 9, 1, 7, 6, 9, 4, 6, 1, 3, 6, 4, 6, 7, 0, 0, 8]
print(list(map(int, str(number))))
max()
# Function prototype: max(iterable, *[, key, default])
# Function Description: returns the largest element in the iteratable object, or the largest of two or more arguments.
# 6
print(min(5, 6))
# 2
print(min([1, 2 , -1]))
min()
# Function prototype: min(iterable, *[, key, default])
# Function Description: returns the smallest element in the iteratable object, or the smallest of two or more arguments.
# 5
print(min(5, 6))
# -1
print(min([1, 2 , -1]))
next()
# Function prototype: next(iterator[, default])
# Function Description: get the next element by calling iterator's "next" () method. If the iterator is exhausted, the given default is returned, and if there is no default, StopIteration is triggered.
iterator = iter([1, 2, 3, 4])
while True:
    try:
        print(next(iterator))
    except StopIteration:
        break
oct()
# Function prototype: oct(x)
# Function Description: converts an integer into an octal string prefixed with "0o".
# 0o10
print(oct(8))
open()
# Function prototype: open(file, mode = 'r', buffering = - 1, encoding = none, errors = none, newline = none, closed = true, Opener = none)
# Function Description: open file and return the corresponding file object. If the file cannot be opened, an OSError is triggered.
fp = open('./vimrc')
print(fp.readline())
fp.close()
ord()
# Function prototype: ord(c)
# Function Description: for a string representing a single Unicode character, an integer representing its Unicode code point is returned.
# 97
print(ord('a'))
# 38472
print(ord('Chen'))
pow()
# Function prototype: pow(x, y[, z])
# Function Description: returns the Y power of X; if z exists, then the remainder of z (more efficient than direct pow(x, y)% z calculation). pow(x, y) in the form of two parameters is equivalent to power operator: x**y.
# 8
print(pow(2, 3))
print()
#Function prototype: print(*objects, sep = ', end =' \ n ', file=sys.stdout, flush=False)
#Function Description: basic output function.
quit()
#Function prototype: quit()
#Function Description: exit the current interpreter environment.
range()
# Function prototype: range(start, stop[, step])
# Function Description: returns the range object, which contains the integer with step as step in the left closed right open interval [start, end].
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(range(1,10)))
reduce()
# Function prototype: reduce(func, sequence[, initial])
# Function Description: the function func with two parameters is applied to each element of sequence seq from left to right in an iterative way, and finally a single value is returned as the result. In Python 2.x, this function is built-in. In Python 3.x, you need to import the reduce function from functools for reuse.
from functools import reduce
# 45
print(reduce(lambda x, y: x+y, list(range(1, 10))))
repr()
# Function prototype: repr(object)
# Function Description: returns a string containing a printable representation of an object. For many types, the string the function will try to return will have the same value as the object generated when the object is passed to eval(), and in other cases, the representation will be a string enclosed in angle brackets, which contains the name of the object type and the additional information usually including the object name and address. Class can control what this function returns for its instance by defining the \. The string object is returned.
# 'MagicOct'
print(repr('MagicOct'))
# {'Magic', 'Oct'}
print(repr({'Magic', 'Oct'}))
reversed()
# Function prototype: reversed(seq)
# Function Description: returns the iterator object after all elements in seq (list, tuple, string, range and other iteratable objects) are reversed.
# [3, 2, 1]
print(list(reversed([1, 2, 3])))
round()
# Function prototype: round(number[, ndigits])
# Function Description: returns the number rounded to the decimal place precision of ndigits. If ndigits is omitted or None, the integer closest to the input value is returned.
# 123.46
print(round(123.456, 2))
# 123
print(round(123.456))
set()
# Function prototype: set([iterable])
# Function Description: convert the iteratable object to a set or generate an empty set.
# {1, 2, 3}
print(set([1, 2, 3]))
# set()
print(set())
setattr()
# Function prototype: setattr(object, name, value)
# Function Description: specifies an existing property or a new property. The function assigns a value to the property, as long as the object allows this operation.
class Temp:
    def __init__(self):
        self.var = 1

obj = Temp()
# 1
print(obj.var)
setattr(obj, 'var' , 123)
# 123
print(obj.var)
sorted()
# Function prototype: sorted(iterable, *, key=None, reverse=False)
# Function Description: returns a new sorted list based on the items in iterable. Reverse is a Boolean value. If set to True, each list element is sorted by a reverse order comparison.
# [3, 2, 1]
print(sorted([1, 3, 2] ,reverse=True))
# [1, 2, 3]
print(sorted([1, 3, 2]))
str()
# Function prototype: str(object=b ", encoding = 'utf-8', errors = 'strict')
# Function Description: returns an object of str version.
# <__main__.Temp object at 0x01371B90>
class Temp:
    def __init__(self):
        self.var = 1
print(str(Temp()))
# 1111
print(str(1111))
sum()
# Function prototype: sum(iterable[, start])
# Function Description: from start, sum the items in iterable from left to right and return the total value. Start defaults to 0. The item of iterable is usually a number, and the start value is not allowed to be a string.
# 6
print(sum([1, 2, 3]))
# 7
print(sum([1, 2, 3],1))
tuple()
# Function prototype: tuple([iterable])
# Function Description: converts the iteratable object to a tuple or generates an empty tuple.
# ()
print(tuple())
# (1, 2, 3)
print(tuple([1, 2, 3]))
type()
# Function prototype: type(object)
# Function Description: when a parameter is passed in, the type of object is returned.
# <class 'str'>
print(type('string'))
zip()
# Function prototype: zip(*iterables)
# Function Description: create an iterator that aggregates elements from each iteratable object. Returns the iterator of a tuple with the ith tuple containing the ith element from each parameter sequence or iteratable object. When the shortest of the input iteratable objects is exhausted, the iterator stops iterating. When there is only one iteratable object parameter, it returns an iterator of a cell group. Without parameters, it returns an empty iterator.
# [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
print(list(zip([1, 2, 3, 4], 'abcd')))
Published 13 original articles, won praise 0, visited 280
Private letter follow

Posted by 448191 on Tue, 21 Jan 2020 09:19:14 -0800