Source of all evil - Python built-in function 1

Keywords: Python encoding ascii Lambda

Built-in function

What's a built-in function? It's a tool that Python provides for us to use directly, such as our print,input,type,id, etc. Up to version 3.6.2 of python.

There are 68 built-in functions. They are provided directly by Python to us. Some of them have been used. Some of them have not been used yet. Another one is that we need to finish learning object-oriented to continue learning. Today, let's take a look at python's built-in functions.

Scope correlation

locals() Returns the name in the current scope

globals() Returns the name in global scope

Iterator correlation

range() Generate data

The next() iterator executes downward once, and the u next_() method is actually used internally to return to the next item of the iterator

iter() Gets the iterator, which is actually acquired internally using the u iter_() method

Execution of string type code

eval() executes string-type code and returns the final result

print(eval('2+8'))
Result:
10

n = 8
print(eval('n + 10'))
Result:
18

exec() executes code of string type

exec('''
for i in range(10):
    print(i)
''')

# We write code in a python-recognizable grammar, and this time we write strings that can be executed as well.


exec(''' 

def func():
    print("444")

func()    

''')

//Result:
444  

compile() mutates the code of the string type, and the code object can be executed by an exec statement or evaluated by eval().

'''
//Description of parameters:

    1.resource  #Method to execute code, dynamic code fragments
    2.file name,File Name for Code Storage,When the first parameter is passed in,Just leave this parameter blank.
    3.Pattern,There are three values
        1.exec When putting some process statements in general
        2.eval resource Store only one evaluation expression
        3.single resource When the stored code interacts.mode Should be single
'''

code = 'for i in range(10):print(i)'

c1 = compile(code,'',mode='exec')
exec(c1)   # No return value with exec

code1 = '1+2+4'
c2 =compile(code1,'',mode='eval')

a = eval(c2) # Use eval to have a return value
print(a)

code = 's = input("Please enter the content");print(s)'

c1 = compile(code,'',mode='single')

exec(c1)  #No return value with exec

Through the above test, we found that as long as exec has no return value, eval has return value, compile is not very common.

Input-output correlation

input() Gets user input

print() Print Output

Memory related

hash() Gets the hash value of the object (int.str,bool,tuple)

id() Gets the memory address of the object

Document operation related

open() is used to open a file and create a file handle

Module correlation

_u import_() for dynamically loading classes and functions

Help

help() Functions are used to view detailed descriptions of functions or module uses

Call correlation

callable() is used to check whether an object is callable. If it returns True, the object may fail. If it returns False, the call is absolutely complete.

View memory properties

dir() Views the built-in attributes of an object by accessing the u dir_() method of the object

Basic data type correlation

Number correlation:

bool() Converts the given data to a bool value, if no value is given. Returns False

int() Converts the given data to an int value and returns 0 if no value is given

float() converts a given data into a float value, which is the last decimal

Compoilex () creates a complex number. The first parameter is the real part, the second parameter is the imaginary part. Or the first parameter describes the complex number directly with a string.

Binary conversion:

bin() Converts the given parameters to binary

otc() converts the given parameters into octal

hex() converts the given parameters into hexadecimal

Digital operations:

Absolute value of ABS

divmode() returns quotient and remainder

Round (rounding)

pow(a,b) calculates the B power of A. If there is a cubic parameter, then the number of third parties is redundant after the 10,000 power.

sum() summation

Minimum value

max() Maximum

Data structure correlation

Lists and meta-ancestors

list() Converts an iterative object into a list

tuple() converts an iterative object into a meta-ancestor

reverse() inverts a sequence and returns the iterator of the inverted sequence

Slice (slice) slices of the list

a = Hello, everybody. I'm Wusong.
s1 = slice(1,8,2)
print(a[s1])

Result:

Home I Wu

String correlation:

str() Converts data into strings

Form () is related to specific numbers, used to calculate various decimal, actuarial, etc.

Character string

# Character string
# print(format('meet','<20'))   #Left alignment
# print(format('meet','>20'))   #Right alignment
# print(format('meet','^20'))   #Centered

//Result:
meet                
                meet
        meet        

numerical value

#numerical value
print(format(3,'b'))    # Binary system
print(format(97,'c'))   # Converting to unicodezif
print(format(11,'d'))   #Decimal system
print(format(56))       #Same as d.
print(format(11,'n'))   #Decimal system
print(format(11,'o'))   #Octal number system

print(format(11,'x'))  # Hexadecimal (lowercase)
print(format(11,'X'))  # Hexadecimal (capital letter)

# Floating point number

print(format(1234567890,'e'))  #Scientific computing, default 6 bits
print(format(123456789,'0.2e'))# Scientific calculation, keep 2 decimal places (lowercase)
print(format(123456789,'0.2E'))# Scientific calculation, keep 2 decimal (upper case)
print(format(1.23456789,'f')) #The decimal point counting method, reserving 6 decimal places
print(format(1.23456789,'0.2f')) # Decimal point counting method, reserve 2 digits
print(format(1.23456789,'0.10f')) # Decimal point counting method, reserve 2 digits
print(format(1.23456789e+1000,'F')) # Decimal point counting method

bytes() Converts strings to bytes types

s = 'Hello, Wu Da.'

bs = s.encode('utf-8')
print(bs)

//Result: b' xe4 xbd xa0 xe5 xa5 xbd xe6 xad xa6 xe5 xa4 xa7'

s1 = bs.decode('utf-8')
print(s1)

//Result: Hello Wuda

bs = bytes(s,encoding='utf-8')
print(bs)

//Result: b' xe4 xbd xa0 xe5 xa5 xbd xe6 xad xa6 xe5 xa4 xa7'
//Encoding strings into utf-8

bytearray() returns a new byte array in which the elements are variable and the values of each element range from 0 to 256.

ret = bytearray('meet',encoding='utf-8')
print(ret)
print(ret[0])

//Result:
bytearray(b'meet')
109

momoryview() View bytes'memory address

s = memoryview('Gentiana'.encode('utf-8'))
print(s)

# Result:
# <memory at 0x000001F332E0E288>

ord() Input character locates with character encoding

print(ord('a'))
print(ord('in'))
print(ord('country'))

Result:
97
20013
22269

Corresponding to the current encoding

chr() Input the position number to find the corresponding character

print(chr(97))  # Find the corresponding character
print(chr(20013))  # Find the corresponding character

# Result:
a
//in

ascii() is the return value in ascii code, not to return\ u

print(ascii('a')) determines that the string is not in the ASCII code table
print(ascii('zhong'))  

Result:
'a'
If'__ 4e2d'does not exist, ret u rn to ___________________________

repr() returns the form of an object's essence

name = 'alex'
Print (repr (name)# returns the representation of the object's essence

Result:
'alex'

Name ='My name is% r'
Print (name%'meet')% R is repr
Result:
My name is'meet'.

Data set

dict() Create a dictionary

set() Creates a collection

frozenset() creates a frozen collection that cannot be added or deleted

Other related

len() returns the number of elements of an object

enumerate() Gets the enumeration object

lst = ['alex','wusir','taibai']

for i,k in enumerate(lst):
    print('This is the serial number.',i)
    print('This is the element.',k)

all() All of the iteratable objects are True, and the result is True.

lst = [1,2,3,4,True,0,False]
lst1 = [1,2,3,4,True]
print(all(lst))

print(all(lst1))

//Result:
False
True

any() One of the iteratable objects is True, which is True.

lst = [1,2,3,4,True,0,False]
lst1 = [1,2,3,4,True]
print(any(lst))

print(any(lst1))

//Result:
False
True

The zip() function is used to take an iterative object as a parameter and package the corresponding elements in the object into a meta-ancestor.

It then returns the contents consisting of these meta-ancestors. If the number of elements in each iterator is not the same, it returns in the shortest length.

lst1 = [1,2,3]
lst2 = ['a','b','c','d']
lst3 = (11,12,13,14,15)

for i in zip(lst1,lst2,lst3):
    print(i)

//Result:
(1, 'a', 11)
(2, 'b', 12)
(3, 'c', 13) 

Lecture after lambda

sorted() sort iterative objects

filter() filtering

map() maps the specified sequence according to the function provided

See material

  https://www.processon.com/view/link/5b4ee15be4b0edb750de96ac  

Posted by richard-elland on Mon, 21 Jan 2019 13:33:12 -0800