1. abs() Take the absolute value function

 #!/usr/bin/env python
# _*_ coding: UTF-8 _*_
# Author:taoke
i = 100
i = -100

2.dict() Create a dictionary

 print(dict({"a":1, "b":2, "c":3}))

3.help() Help function

4.min()  Returns the smallest item iterable Or the smallest two or more parameters .


Running results :-2

5.setattr() Assign values to the corresponding properties of an object

setattr(x, 'foobar', 123) Equate to x.foobar = 123

6.all() All for True return True, No one returns Flase


Running results :


7.ascii() Change a memory object into a printable string form

8.bin() Convert an integer to a binary string


Running results :


9.dir() When a function has no arguments , Returns the variables in the current range 、 List of types of methods and definitions ; With parameters , Return the properties of the parameter 、 Method list . If the parameter contains a method __dir__(), This method will be called . If the parameter does not contain __dir__(), This method will maximize the collection of parameter information .


Running results :

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

10 hex() Convert an integer object to a hexadecimal string representation , Such as 0x The format of .

 #!/usr/bin/env python
# _*_ coding: UTF-8 _*_
# Author:taoke
# Convert an integer to a hexadecimal string

11 next()  Returns the next entry for the iterator

 #!/usr/bin/env python
# _*_ coding: UTF-8 _*_
# Author:taoke
n = iter([i*i for i in range(10)])
for i in range(10):

Running results :


12 slice() Slicing operation

slice[start, stop, step]: Create a slice type . slice(none) It's equivalent to a colon ':'. usage :

s = slice(1,3), a=[1,2,3,4,5,6,7]. be a[s] == a[1:3] == [2, 3]

Multiple axis You just need to slice slice Type variable list Just get up ~: [s1,s2,...]

Can be used to specify axis The section of . For example, requirements a In the axis A slice of an axis , from start To end:

slc = [slice(None)]*len(a.shape)

slc[axis] = slice(start,end)

a[slc] That is .

13 any(): Returns... When an empty iteratable object is passed in False, When any of the iteratable objects is not False, Then return to True

# One of the iteratable objects is True
# None of the iteratable objects is True

Running results :


14 divmod():divmod(a,b) Realization a Divide b, Then return the tuple of quotient and remainder . If two parameters a,b Are integers. , So we'll use integer division , The result is equivalent to (a//b, a % b). If a or b Is a floating point number , amount to (math.floor(a/b), a%b).


Running results :

(5, 0)
(5.0, 0.12000000000000455)

15 id() Get memory address

 vir1 = 1232
vir2 = 1232
vir3 = 22222

Running results :


16 object()

Official documents :

Return a new featureless object. object is a base for all classes. It has the methods that are common to all instances of Python classes. This function does not accept any arguments.

Note:object does not have a __dict__, so you can’t assign arbitrary attributes to an instance of the object class.

translate :

Returns a new featureless object . Objects are the foundation of all classes . It has all the Python Class instances are common methods . This function takes no arguments .

Be careful : Objects have no __dict__, So you can't assign any attribute to an instance of an object class .

17 sorted()

sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list

The first parameter is the iteratable object , The following parameters have default values , The main points are as follows :

1、cmp, The function of comparison , This has two parameters , The values of the parameters are taken from the iteratable objects , The rule that this function must follow is , Greater than returns 1, Less than returns -1, Is equal to returns 0

2、key, It's basically a comparison element , There is only one parameter , The parameters of the specific function are taken from the iterable object , Specifies an element in an iterable object to sort

3、reverse, Whether to reverse , Not reversed by default

 def cmp_value(x,y):
if x > y :
return 1
elif x < y:
return -1
return 0
so = sorted('this is a string'.split(' '),cmp=cmp_value)
print so

Running results :

['a', 'is', 'string', 'this']

18 ascii()  Returns a printable string representation of an object . When it comes to non ASCII Code time , Will be output \x,\u or \U And so on .

a = ascii(object)

Running results :

<class 'object'>
<class 'str'>

19 enumerate()  Function is used to traverse a data object ( As listing 、 Tuples or strings ) Combined into an index sequence , List both data and data index , Generally used in for Cycle of .

 list1 = [1,2,3,4,5,6]
for i,j in enumerate(list1):

20 input()  To get input from the console .

 name = input(" Please enter a name :")
print(" name :%s "%name)

Running results :

Please enter a name :taoke
name :taoke

21 oct()  Function to convert an integer to 8 Base string .

 t = oct(123)

Running results :

<class 'str'>

22 staticmethod()  Returns a static function object , Mainly used as static function modifiers . The feature of static functions is that they can be accessed directly through the class namespace , That is to say, you can use this function without defining class instances ; It can also be accessed through class instances . This one JAVA or C++ The static functions in are the same .

 class testclass(object):
def func1(a,b):
print(a , b) testclass.func1(1,2)

Running results :

1 2

23 bin()  Convert an integer x Is a binary string representation . If parameters x Not an integer object , It can be overloaded __index__() Function to return an integer .


Running results :

<class 'str'>

24 eval()  The string str Evaluate as a valid expression and return the result

 str = input(" Please enter :")
obj = eval(str)

Running results :

Please enter :1+2+3+4

25 int()  Function is used to convert a string to an integer


Running results ;


26 open()  Function to open a file , Create a  file  object , Related methods can be called to read and write .

27 str() Function converts an object into a human readable form .

28 bool() function

 # Integers 0, Floating point numbers 0.0, An empty list , An empty tuple , An empty dictionary , An empty string , Are all False
print bool(0.0),bool(0),bool([]),bool(()),bool({}),bool('')
# Positive numbers , Negative numbers are True
print bool(8),bool(-3),bool(-3.9),bool(9.8)
# Non empty list , Nonempty tuples , Non empty dictionary , All non empty strings are True
print bool([2,3]),bool((3,4)),bool({'name':'song'}),bool('python')

Running results :

False False False False False False
True True True True
True True True True

10 getattr() 、hasattr()、getattr() and delattr()

setattr(): Set a method or property of an object 
getattr(): Using a method or property of an object
hasattr(): Determine whether an object has a method or property
delattr(): Delete a method or property of an object

Python More articles on built-in methods

  1. Python The built-in method is explained in detail

    1. String built-in method details Why have strings ? Relative to tuples . List etc. , For the definition of a unique type , Strings have the simplest form . Strings are often received as variables , Variable name . You can see all the built-in methods for Strings , Such as : 1> count ...

  2. Anonymous functions python Built-in methods (max/min/filter/map/sorted/reduce) Process oriented programming

    Catalog Function advanced three 1. Anonymous functions 1. What is anonymous function 2. The syntax of anonymous functions 3. Some methods that can be used with anonymous functions 2. python Interpreter built-in methods 3. exception handling Process oriented programming Function advanced three 1. Anonymous letters ...

  3. python Built-in methods 、 Data serialization

    abc(*args, **kwargs) Take the absolute value def add(a,b,f): return f(a)+f(b) res = add(3,-6,abs) print(res) all(*args, ...

  4. python Built-in methods

    1. brief introduction This is my blog guide for a few months , The theme is Magic methods . What is magic method ? They're in object-oriented Python It's everywhere . They are some that allow you to add " magic " Special method . They are often ...

  5. Python The time complexity of built-in methods ( turn )

    original text :http://www.orangecube.net/python-time-complexity This article is translated from Python Wiki This article is based on GPL v2 agreement , Please keep this agreement . This page covers Pyt ...

  6. Python The time complexity of built-in methods

    Reprinted from :http://www.orangecube.NET/Python-time-complexity This page covers Python The time complexity of some methods in ( Or call it " Great Europe "," ...

  7. Python Built-in methods / function

    abs() Returns the absolute value of the number . abs(x) all() It is used to judge the given iterative parameters iterable Whether all elements in are TRUE, If it's a return True, Otherwise return to False. Except that the elements are 0. empty . ...

  8. python Built in methods

    Mathematical operations abs: Find the absolute value of the value >>> abs(-2) 2 divmod: Returns the quotient and remainder of two values >>> divmod(5,2) (2, 1) >> ...

  9. Python Built-in methods new

    class Dog(object): def __new__(self): print("i am new .") def __init__(self): print(" ...

Random recommendation

  1. solve MySQL Cluster adopt One of them MySqld When a node creates a new table , other MySqld node The problem of not seeing the contents of the table

    problem : All in all 4 individual MySqld node , When creating a new table through one of the nodes , Find others  MySqld node Can't find the table content , That is, the table is not synchronized . Solution : It's mainly because when you create a new table , The chosen Watch engine It's a mistake , Can only ...

  2. front end html+css The fourteenth day of

    One .HTML 1.HTML What is it? ? Hypertext Markup Language, Chinese is also hypertext markup language . HTML It's a set of rules , A set of browser recognition rules . 2. developer : (1) Study Html gauge ...

  3. sql Group merge field repeats sql for xml path

    -------------------------( Scenario description ) As we work with data , It's possible to come across a situation like this : Id                Name 1                  a,b 2  ...

  4. amoeba Read and write separation

    amoeba The operating environment of the system depends on java Of jdk: Following execution amoeba The installation doesn't go away # mkdir /usr/local/src/amoeba Upload files :amoeba-mysql-binary-2.2.0. ...

  5. Applet to get the current page URL

    var pages = getCurrentPages() // Get loaded page var currentPage = pages[pages.length-1] // Get the object of the current page var url ...

  6. [No000011B] Why do some programmers go through it quietly 35 Middle age crisis ?

    Today's sharing is for some seniors who have gone through the middle-aged crisis , Look at them , How the transition is elegant . If you want to go on the road of program all the time , I suggest that you finish reading . Article slightly longer . Character one : Chen Rui , Former R & D Manager of Baidu , Ctrip customized travel CTO From programmer to architect to manager ...

  7. CodeCraft-19 and Codeforces Round #537 (Div. 2) D Multiple permutations + reverse 01 knapsack + Offline processing

    https://codeforces.com/contest/1111/problem/D Multiple permutations + reverse 01 knapsack The question : Give you a string (n<=1e5,n For the even ), Yes q A asked , Ask two at a time ...

  8. JDBC technology ( Convergence page )

    JDBC representative Java Database connection (Java Database Connectivity), It is used for Java Standard for database-independent connections between programming languages and databases Java API, let me put it another way :JDBC Is used in Java ...

  9. About WizTools.org RESTClient Use

    Today, share a good test service Tools for , useful Provide two ways to use this Dongdong . The first method adopt cmd Command window . (1)cd C:\Users\li_weifeng\Desktop\c4d2( File in ...

  10. WCF Endpoint not found

    It's all equipped with , Still can't find ,config The file was not reloaded , Cause unknown , You can only recompile it , Just fine .... Follow up to find out why