Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the Python built-in functions

2025-01-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains the "what Python built-in functions", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "which Python built-in functions" bar!

It's related to numbers.

1. Data type

Bool: Boolean (True,False)

Int: integer (integer)

Float: floating point (decimal)

Complex: plural

two。 Binary conversion

Bin () converts the given parameter to binary

Otc () converts the given parameter to octal

Hex () converts the given parameter to hexadecimal

Print (bin (10)) # binary: 0b1010 print (hex (10)) # hexadecimal: 0xa print (oct (10)) # Octal: 0o12

3. Mathematical operation

Abs () returns an absolute value

Divmode () returns quotient and remainder

Round () is rounded

Pow (a, b) finds the b power of a, if there are three parameters. Then take the remainder of the third number after finding the power.

Sum () summation

Min () to find the minimum

Max () to find the maximum

Print (abs (- 2)) # absolute: 2 print (divmod (20)) # Quotient and remainder: (6) print (round (4.50)) # rounded: 4 print (round (4.51)) # 5 print (pow (10L2)) # if the third parameter is given. Indicates the final remainder: 1 print (sum ([1 print 2 3) # summation: 55 print (min (5 3)) # find the minimum: 2 print (max (7 print)) # find the maximum: 15

Related to data structure

1. Sequence

(1) lists and tuples

List () converts an iterable object into a list

Tuple () converts an iterable object into a tuple

Print (list (1, 2) # (1) (2)) # [1, 2, 3, 3, 4, 5, 6] print (tuple ([1, 2, 3, 4, 5, 5) # (1, 2, 3, 4, 5, 5)) # (1, 2, 3, 4, 5, 5)

(2) related built-in functions

Reversed () flips a sequence and returns the iterator of the flipped sequence.

Slicing of slice () list

Lst = "Hello" it = reversed (lst) # will not change the original list. Returns an iterator with a design rule print (list (it)) # ['Ah', 'good', 'you'] lst = [1,2prime3,4,5,6,7] print (LST [1: 3:1]) # [2magor3] s = slice (1,3,1) # slicing print (LST [s]) # [2prime3]

(3) string

Str () converts data to a string

Print (str (123) + '456') # 123456

Format () is related to specific data and is used to calculate all kinds of decimals, actuaries, etc.

S = "hello world!" Print (format (s, "^ 20")) # print (format (s, "20")) # align right # hello world! # hello world! # hello world! Print (format (3,'b')) # binary: 11 print (format (97,'c')) # converted to unicode characters: a print (format (11,'d')) # binary: 11 print (format (11,'o')) # Octal: 13 print (format (11,'x')) # hexadecimal (letters written): B print (format (11) 'X')) # hexadecimal (capital letters): B print (format (11,' n')) # and d samples: 11 print (format (11)) # and d samples: 11 print (format (123456789,'e')) # scientific counting. 6 decimal places are retained by default: 1.234568e+08 print (format (123456789, '0.2e')) # Scientific counting. Keep 2 decimal places (lowercase): 1.23e+08 print (format (123456789, '0.2e')) # Scientific counting. Keep 2 decimal places (uppercase): 1.23E+08 print (format (1.23456789,'f')) # decimal point counting. Keep 6 decimal places: 1.234568 print (format (1.23456789, '0.2f')) # decimal point counting. Keep 2 decimal places: 1.23 print (format (1.23456789, '0.10f')) # decimal point counting. Keep 10 decimal places: 1.2345678900 print (format (1.23456789e+3,'F')) # decimal point counting. Output INF:1234.567890 when it is very large

Bytes () converts a string to a bytes type

Bs = bytes ("have you eaten today", encoding= "utf-8") print (bs) # b'\ xe4\ xbb\ x8a\ xe5\ xa4\ xa9\ xe5\ x83\ xe9\ xa5\ xad\ xe4\ xba\ x86\ xe5\ x90\ x97'

Bytearray () returns a new byte array. The element of this number is variable, and the value range of each element is [0256).

Ret = bytearray ("alex", encoding = 'utf-8') print (ret [0]) # 97 print (ret) # bytearray (bounded Alexa') ret [0] = 65 # assign position An of 65 to ret [0] print (str (ret)) # bytearray (bounded Alex')

Ord () input characters to find the position with character encoding

Chr () input the position number to find the corresponding character

Ascii () is the ascii code that returns the value or u

Print (ord ('a')) # letter a code point in the coding table: 97 print (ord ('middle')) # 'middle' position in the coding table: 20013 print (chr (65)) # known code point, what is the character: a print (chr (19999)) # "for i in range (65536): # print out the characters print (chr (I)) from 0 to 65535 End= ") print (ascii (" @ ")) #'@'

Repr () returns the string form of an object

S = "Today\ nate% s meals\ t meal"% 3 print (s) # Today # ate 3 meals print (repr (s)) # output as is, filter out escape characters\ n\ t\ r regardless of% sign% # 'today\ n3 meals\ t'

two。 Data set

Dictionary: dict creates a dictionary

Collections: set creates a collection

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

3. Correlation built-in function

Len () returns the number of elements in an object

Sorted () sorts iterable objects (lamda)

Syntax: sorted (Iterable, key= function (collation), reverse=False)

Iterable: iterable object

Key: collation (collation function). Within sorted, each element in the iterable object is passed to the parameter of this function. Sort according to the results of the function operation

Reverse: whether it is a flashback. True: flashback, False: positive order

Lst.sort () # sort is a method in list print (lst) # [1,5,5,6,7,9,12,13,18] ll = sorted (lst) # built-in function. A new list is returned to you. The new list is sorted print (ll) # [1, 5, 5, 6, 7, 9, 12, 13, 18] L2 = sorted (lst,reverse=True) # reverse print (L2) # [18, 13, 12, 9, 7, 6, 5, 5, 1] # sort the list by string length lst = ['one',' two', 'three',' four', 'five' 'six'] def f (s): return len (s) L1 = sorted (lst, key=f,) print (L1) # [' one', 'two',' six', 'four',' five', 'three']

Enumerate () gets the enumerated object of the collection

Lst = ['one','two','three','four','five'] for index, el in enumerate (lst,1): # fetches the index with the element. The index starts from 0 by default. You can change print (index) print (el) # 1 # one # 2 # two # 3 # three # 4 # four # 5 # five

The all () iterable object is all True, and the result is True.

One of the any () iterable objects is True, and the result is True.

Print (all) # True print (any)) # True

The zip () function is used to take iterable objects as parameters, package the corresponding elements in the object into a tuple, and then return a list of these tuples. If the number of elements of each iterator is not the same, the length of the return list is the same as the shortest object.

Lst1 = [1,2,3,4,5,6] lst2 = ['drunken hometown ballad', 'donkey gets water', 'spring of cattle herding class', 'beautiful life', 'defender', 'life of abandoned pine nuts'] lst3 = ['USA', 'China', 'France', 'Italy', 'Korea', 'Japan'] print (zip (lst1, lst1) Lst3) # for el in zip (lst1, lst2, lst3): print (el) # (1, 'drunken Folk songs', 'USA') # (2, 'Donkey gets Water', 'China') # (3, 'Spring of cattle herding Class', 'France') # (4, 'Beautiful Life', 'Italy') # (5, 'defender', 'Korea') # (6 'The life of the abandoned pine nut', 'Japan')

Fiter () filtering (lamda)

Syntax: fiter (function. Iterable)

Function: the function used to filter. Elements in iterable are automatically passed to function in iterable lter. Then judge whether to retain this data according to the True or False returned by function. Iterable: iterable object.

Def func (I): # judge odd return I% 2 = = 1 lst = [1 filter (func, lst) # L1 is an iterator print (L1) # print (list (L1)) # [1,3,5,7,9]

Map () maps the specified sequence column (lamda) according to the function provided.

Syntax: map (function, iterable)

Each element in an iterable object can be mapped. To execute function separately

Def f (I): return i lst = [1, it 2, 3, 4, 5, 6, 7,] it = map (f, lst) # passes each element of the iterable object to the previous function for processing. The result of the processing will be returned as an iterator print (list (it)) # [1, 2, 3, 4, 5, 6, 7]

Related to scope

Locals () returns the name in the current scope

Globals () returns the name in the global scope

Def func (): a = 10 print (locals ()) # content in the current scope print (globals ()) # content in the global scope print ("a lot of content today") func () # {'name__':: 10} # {' _ name__':'_ main__','_ doc__': None,'_ package__': None '_ _ loader__': #, #' _ _ spec__': None,'_ _ annotations__': {},'_ _ builtins__':,'_ _ file__': 'D:/pycharm/ exercise / week03/new14.py',' _ _ cached__': None, # 'func':} # there are a lot of content today

Related to iterator generator

Range () generates data

The next () iterator executes down once, and the _ _ next__ () method is actually used internally to return the next item of the iterator.

Iter () gets the iterator, and the internal actually uses the _ _ iter__ () method to get the iterator

For i in range: print (I) # 15 # 10 # 5 # 0 lst = [1 Magi 2 # 10 # 5 # 0] it = iter (lst) # _ iter__ () get the iterator print (it.__next__ ()) # 1 print (next (it)) # 2 _ next__ () print (next (it)) # 3 print (next (it)) # 4

Execution of string type code

Eval () executes code of type string. And return the final result

Exec () executes code of type string

Compile () encodes the code of type string. Code objects can be executed through exec statements or evaluated by eval ()

S1 = input ("Please enter aqb:") # input: 8: 9 print (eval (S1)) # 17 can execute the code dynamically. The code must have a return value S2 = "for i in range (5): print (I)" a = exec (S2) # exec execution code does not return anything # 0 # 1 # 2 # 3 # 4 print (a) # None # dynamic execution code exec ("" def func (): print ("I am Jay Chou") ") func () # I am Jay Chou Code1 = "for i in range (3): print (I)" com = compile (code1) Mode= "exec") # compile will not execute your code. Just compile exec (com) # and execute the compilation result # 0 # 1 # 2 code2 = "5 minutes 6, 7" com2 = compile (code2, ", mode=" eval ") print (eval (com2)) # 18 code3 =" name = input ('Please enter your name:') "# input: hello com3 = compile (code3,", mode= "single") exec (com3) print (name) # hello

Input and output

Print (): printout

Input (): get the content output by the user

Print ("hello", "world", sep= "*", end= "@") # sep: what connection does the printed content use, end: what ends with # hello*world@

Memory dependent

Hash (): gets the hash value of the object (int, str, bool, tuple). Hash algorithm: (1) the purpose is unique. (2) dict search efficiency is very high, hash table. Trading space for time consumes more memory.

S = 'alex' print (hash (s)) #-168324845050430382 lst = [1, 2, 3, 4, 5] print (hash (lst)) # error, the list is id (): get the memory address of the object s =' alex' print (id (s)) # 2278345368944

File operation related

Open (): used to open a file and create a file handle

F = open ('file',mode='r',encoding='utf-8') f.read () f.close ()

Module correlation

_ _ import__ (): used to dynamically load classes and functions

# Let the user enter a module to import import os name = input ("Please enter the module you want to import:") _ _ import__ (name) # you can import the module dynamically

Help

Help (): a function is used to view a detailed description of the purpose of a function or module

Print (help (str)) # View the purpose of the string

Call related

Callable (): used to check whether an object is callable. If True is returned, the call to object may fail, but if False. The call will never succeed.

A = 10 print (callable (a)) # False variable a cannot be called # def f (): print ("hello") print (callable (f)) # True function can be called

View built-in properties

Dir (): view the built-in properties of the object, accessing the _ _ dir__ () method in the object

Print (dir (tuple)) # Thank you for your reading. This is the content of "what are the built-in functions in Python". After the study of this article, I believe you have a deeper understanding of what Python built-in functions are, and the specific usage still needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 253

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report