Python's built-in functions

Source: Internet
Author: User
Tags iterable ord pow string format

Name of function Function description Example
ABS () Returns the absolute value of a number ABS (-45)
Divmod () Combine the divisor and remainder operations to return a tuple containing quotient and remainder Divmod (7,2) return: (3,1)
Raw_input () Get console input, treat all inputs as strings, return string types

A=raw_input ("input=")

Input=abc

Type (a) #<type ' str ' >

Input () Get console input, want to be able to read a valid Python expression, that is, the input string, you need to enclose in quotation marks, otherwise report syntax error

A=raw_input ("input=")

INPUT=ABC #会报错

Staticmethod () Declaring a method as a static method, a class can call a static method without instantiating it, or an instantiation can invoke

Class C (object):

@staticmethod

def f ():

Print ("Staticmethod")

C.F () #静态方法无需实例化

CObj = C ()

COBJ.F () #实例也可调用

All () Used to determine whether all elements in the given iteration parameter iterable are not 0, ', false, or iterable null, or False if True is returned

All ([' A ', ' B ']) #True

All ([' A ', '] ') #Flase

All ([0,1,2]) #False

All ([]) #True

All (()) #True

Int (x,base=10) The user converts a string or number to reshape, and base identifies the binary

int () # defaults to 0

Int (3.6) # 3

Int (' A ', ') #18

Ord () Returns the decimal integer of the corresponding character Ord (' a ') #97
UNICHR () Returns the Unicode character

Unicode ($) # u ' A '

STR () Returns the string format of an object

Dict={' A ', ' B ', ' C '}

STR (dict) # "{' A ', ' B ', ' C '}"

Any () Used to determine whether the given iteration parameters iterable are all empty objects, and if all are empty, 0, False, return false, otherwise true

Any ([' A ', ' B ', ' C ']) # True

Any ([' A ', ' ', ' C ']) #True

Any ([0, ', False]) #False

Any ([]) #False

Any (()) #False

Eval () Used to execute a string expression and return the value of the expression

X=7

Eval (' 3*x ') # 21

Eval (' Pow (2,2) ') #4

Eval (' the ' + + ') #4

Isinstance () Used to determine whether an object is a known type, it is assumed that the subclass is a type of parent class, considering the inheritance relationship

a=2

Isinstance (A,int) #True

Isinstance (A,STR) #False

Isinstance (A, (str,int,list)) #True

Class A:pass

Class B (A):p

Isinstance (B (), A) #True

Type (B ()) = = A #Flase

Type () Used to determine the type of an object and does not consider the subclass to be a parent class type, regardless of the inheritance relationship Type (1) # <type ' int ' >
POW () The Math module calculates the y-side of X, and if z exists, then the result is modeled, equivalent to the POW (x, y)%z, which generally returns the float type

Math.pow (100,2) #10000.0

Math.pow (100,-2) #0.0001

SUM () Sum, SUM (Iterable[,start]), start specifies the parameter to add, no default is 0

SUM ([0,,1,2]) #3

SUM ([2,3,4],1) #10元组计算总和后再加1

Basestring () This method is a superclass of STR and Unicode (parent class), is also an abstract class, cannot be called and instantiated, but can be used to determine whether an object is a str or an instance of Unicode, isinstance (obj, basestring) is equivalent to Isinstance ( obj, (str, Unicode)) Isinstance("Hello World", basestring)
ExecFile () Used to execute a file

ExecFile (' test.py ') is equivalent to

With open (' test.py ', ' R ') as F:exec (F.read ())

Issubclass () Issubclass (Class,classinfo), determines whether the class is a subclass of ClassInfo, returns True, or returns false

Class A:pass

Class B (A):p

Issubclass (b,a) #返回True

Bin () Returns a binary representation of an integer int or long int

Bin (Ten) # ' 0b1010 '

Bin (#) # ' 0b10100 '

ITER () function to build iterators

lst=[1,2,3]

For I in ITER (LST):p rint (i)

Tuple () The function converts the list to a tuple, and a tuple of the dictionary key is returned for the dictionary; The tuple returns the tuple itself; the elements of the tuple cannot be modified

Tuple ([1,2,3,4]) # (1,2,3,4)

Tuple ({1:2,3:4}) # (1,3)

List () Convert a tuple to a list

List ((*, ' xyz ', ' abc ')

# [123, ' XYZ ', ' abc ']

BOOL () Converts the given parameter to a Boolean type, and returns False if there are no arguments

BOOL () # False

BOOL (0) # False

BOOL (1) # True

Filter () The function is used to filter the sequence, filter out non-conforming elements, and return a new list of eligible elements, two parameters, the first is a function, the second is a sequence; filter (function,iterable)

Filter out all cardinality

def is_odd (n): return n%2 = = 1

NewList = Filter (is_odd,[1,2,3,4,5,6])

#newlist = [1,3,5]

Len () Returns the length of a string or the number of items

str = "Runnoob"

Len (str) #6

L = [1,2,3,4,5]

Len (l) # 5

Range () Can create a list of integers, typically used in a For loop, range (Start,stop[,step])

Range (5) # [0,1,2,3,4,5]

Range (1,5) # [1,2,3,4,5]

Range (0,6,2) # [0,2,4,6]

Float () convert integers and strings to floating-point numbers

Float (1) # 1.0

Float (112) # 112.0

Float (' 123 ') # 123.0

Callable (object) Used to check if an object is callable, returning true,object may still fail to invoke, and calling object will never succeed if it returns false

Callable (0) # False

Callable ("Baidu") # False

def add (A, B): Return a+b

Callable (ADD) # True

Format ()

function Str.format () for formatting strings, which enhances the function of string formatting

1.format function can accept unlimited number of parameters, position can also be out of order

2. Parameters can also be set

1. Position not in order

"{} {}". Format ("H", "W") # "H W"

' {0}{1} '. Format ("H", "W") # "H W"

' {1}{0}{0} '. Format ("H", "W") # "W H H"

2. Setting parameters

"Site name: {name}, Address: {URL}". Format (name= "Baidu", Url= "www.baidu.com")

Setting parameters through a dictionary

site = {"Name": "Baidu", "url": "Www.baidu.com"}

"Site name: {name}, address {URL}". Format (**site)

Setting parameters by List index

My_list = [' Baidu ', ' www.baidu.com ']

"Site name: {0[0]}, address {0[1]}". Format (my_list) #0是必须的

Locals ()

Returns all local variables of the current position as a dictionary type

For functions, methods, lambda functions, classes, and class instances that implement the __call__ method, it returns true

def Baidu (Arg):

Z=1

Print (Locals ())

Baidu (4)

#{' Z ': 1, ' arg ': 4} Returns a dictionary of name/value pairs

:"

Python's built-in functions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.