Common function methods in Python

Source: Internet
Author: User
Tags abs inheritance iterable mathematical constants numeric value ord pow square root
Type Conversions
function Description Example
int (x [, Base]) Converts x to an integer, base optional, binary, default to Decimal
Float (x) Convert x to a floating-point number
Complex (real [, Imag]) Create a complex number Complex (1, 2)-> (1 + 2j)
STR (x) Convert object x to String
Tuple (s) Converts a sequence s to a tuple
List (s) Converts the sequence s to a list
Set (s) Convert to Variable set
Frozenset (s) Convert to immutable set
Dict (d) Create a dictionary
Chr (x) Converts an integer to a character Chr (->) A
Ord (x) Converts a character to its integer value Ord (' a ')-> 97
REPR (x) Converts an object x to an expression string Repr ({' Runoob ': ' runoob.com ', ' Google ': ' google.com '})-> "{' Google ': ' google.com ', ' runoob ': ' Runoob.com '}"
eval (str) Used to compute a valid Python expression in a string, and returns an object Eval (' 3 * 7 ')-> 21
Mathematical Functions
function Description
ABS (x) Returns the absolute value of a number, such as ABS (-10) Returning 10
Max (x1, x2,...) Returns the maximum value of the given parameter, which can be a sequence
Min (x1, x2,...) Returns the minimum value of a given parameter, which can be a sequence
Pow (x, y) The value after the x**y operation
Round (x [, N]) Returns the rounded value of a floating-point number x, such as an n value, that represents the digits rounded to the decimal point
The following belong to the random module
Choice (seq) Pick an element randomly from a sequence of elements, such as random.choice ([' l ', ' u ', ' O ']), pick an element from the list
Randint (Start, stop) Gets a random integer, such as Random.randint (1,10), from a specified range, randomly generating an integer from 1-10
Randrange ([Start,] stop [, step]) Gets a random number from the specified range, in a collection that is incremented by the specified cardinality, with a cardinality default of 1
Random () Randomly generates the next real number, which is in the range of [0,1]
Uniform (x, Y) Randomly generates the next real number, which is within [x,y]
Seed ([x]) Change the seed of the random number generator. If you don't understand its rationale, you don't have to specifically set Seed,python to help you choose Seed.
Shuffle (LST) To sort all the elements of a sequence randomly
The following belong to the math module
Ceil (x) Returns the upper integer of a number, such as Math.ceil (4.1) Returning 5
EXP (x) Returns the X power (ex) of E, as MATH.EXP (1) returns 2.718281828459045
Fabs (x) Returns the absolute value of a number, such as Math.fabs (-10) Returning 10.0
Floor (x) Returns the lower integer of a number, such as Math.floor (4.9) Returning 4
Log (x) such as Math.log (MATH.E) return to 1.0,math.log (100,10) return 2.0
LOG10 (x) Returns the logarithm of an X with a base of 10, such as MATH.LOG10 (100), returning 2.0
MODF (x) Returns the integer and decimal parts of x, and the values of the two parts are the same as x, and the integral part is represented by a floating-point type
Trigonometric Parts
sqrt (x) Returns the square root of a number X
Sin (x) The sine value of the returned X radians
ASIN (x) Returns the inverse chord Radian value of X
COS (x) Returns the cosine of the arc of X
ACOs (x) Returns the inverse cosine radian value of x
Tan (x) Returns the tangent of x radians
Atan (x) Returns the tangent radian value of x
Atan2 (y, x) Returns the tangent value of the given X and Y coordinate values
Degrees (x) Converts radians to angles, such as degrees (MATH.PI/2), returning 90.0
Radians (x) Convert Angle to radians
Hypot (x, y) Returns Euclidean norm sqrt (x*x + y*y)
Mathematical Constants Section
Pi Mathematical constant Pi (pi, usually represented by PI)
E Mathematical constants E,e i.e. natural constants (natural constants)
string-related
function Description Example
Len (String) return string length
Capitalize () Converts the first character of a string to uppercase
Count (str, Beg=0,end=len (string Returns the number of times that STR appears in a string, and returns the number of STR occurrences within a specified range if beg or end specifies
StartsWith (str, Beg=0,end=len (String)) Returns True if the string is beginning with obj, or False. If beg and end specify a value, the specified range is checked
EndsWith (suffix, beg=0, End=len (String)) Checks whether the string ends with suffix and, if beg or end specifies, checks whether the specified range ends with suffix, returns True if it is, or returns False
Find (str, beg=0 End=len (String)) Detects whether STR is contained in a string, and if the range beg and end is specified, checks whether it is contained within the specified range, or returns 1 if it contains the index value that returns the start.
Isalnum () Returns True if the string has at least one character and all characters are letters or numbers, or False
Isalpha () Returns True if the string has at least one character and all characters are letters, otherwise it returns FALSE, whether the pure letter
IsDigit () Returns True if the string contains only numbers or False if the number is pure
Islower () Returns True if the string contains at least one case-sensitive character, and all of these (case-sensitive) characters are lowercase, or False
Isupper () Returns True if the string contains at least one case-sensitive character and all of these (case-sensitive) characters are uppercase, otherwise returns FALSE
Isspace () Returns True if the string contains only white space, otherwise returns FALSE
Join (SEQ) Merges all elements in a seq (a string representation) into a new string, using the specified string as a delimiter s = "-"; seq = ("L", "U", "O");p rint (S.join (seq))-> L-u-o
Lower () All uppercase characters in the conversion string are lowercase
Upper () lowercase letters in the conversion string are uppercase
Strip ([chars]) Deletes a space or a specified character on either side of a string
Lstrip () Deletes a space or a specified character to the left of a string
Rstrip () Deletes a space or a specified character to the right of a string
Replace (old, new [, Max]) Replaces the str1 in a string with str2, and if Max specifies, replaces Max Times
Split (str, num=string.count (str)) Num=string.count (str)) intercepts a string with Str as a delimiter, and if NUM has a specified value, only the NUM substring is intercepted str = "This is string Example....wow!!!"; Print (Str.split ())-> [' This ', ' is ', ' string ', ' EXAMPLE....WOW!!! ']
List Related
function Description
Len (list) Number of list elements
Max (list) Returns the maximum value of a list element
MIN (list) Returns the minimum value of a list element
List (seq) Convert a tuple to a list
List.append (obj) Add a new object at the end of the list
List.count (obj) Count the number of times an element appears in the list
List.extend (seq) Append multiple values in another sequence at the end of the list (extending the original list with the new list), similar to + operations
List.index (obj) Find the index position of the first occurrence of a value from the list
List.insert (index, obj) Insert an object into a list
List.pop (Index) Removes an element from the list (the default last element) and returns the value of the element
List.remove (obj) Removes the first occurrence of a value in a list
List.reverse () Reverse elements in a list
List.sort ([func]) Sort the original list
List.clear () Empty list
List.copy () Copy List
Tuple related
function Description
Len (tuple) Count the number of tuple elements
Max (tuple) Returns the maximum value of an element in a tuple
MIN (tuple) Returns the minimum value of an element in a tuple
Tuple (SEQ) Convert a list to a tuple
Dictionaries
function Description
Len (dict) Calculates the number of dictionary elements, that is, the total number of keys
STR (DICT) Output dictionary, expressed as a printable string
Dict.fromkeys () Creates a new dictionary, the key of the dictionary for the elements in the sequence seq, and Val is the initial value for all keys in the dictionary.
Dict.setdefault (Key, Default=none) is similar to get (), but if the key does not exist in the dictionary, the key is added and the value is set to default, similar to Dict[key]=obj
Dict.get (Key, Default=none) Returns the value of the specified key, if the value does not return a default value in the dictionary, Dict[key]
Key in Dict Returns False if the key returns true in the dictionary Dict
Dict.values () Returns all values in a dictionary as a list
Dict.keys () Returns a dictionary with a list of all the keys
Dict.items () Returns a traversal (key, value) tuple array as a list
Dict.update (DICT2) Update the key/value pairs of the dictionary dict2 to dict, the same key will overwrite the update
Dict.clear () Delete all elements in a dictionary
Dict.copy () Returns a shallow copy of a dictionary
Pop (Key[,default]) Deletes the value of the dictionary given key keys, and returns the value that is deleted. The key value must be given. Otherwise, return the default value
Popitem () Randomly returns and deletes a pair of keys and values from the dictionary (general deletion of the end pair)
built-in Functions
function Description Example
ABS () Returns the absolute value of a number
Min () Returns the minimum value of a given parameter, which can be a sequence
Max () Returns the maximum value of the given parameter, which can be a sequence
Help () function to view a detailed description of the purpose of a function or module Help (' str ') # to see how the STR data type helps
SetAttr () Used to set the property value, which must exist SetAttr (person, ' sex ', ' M ') # Set Property bar value
GetAttr () Used to return an object property value
Delattr () For deleting properties, delattr (x, ' Foobar ') equals del X.foobar
Dir () Returns a list of the variables, methods, and definitions in the current scope, with parameters, and returns the properties of the parameter, a list of methods, when not with parameters. If the parameter contains method dir(), the method is invoked. If the parameter does not contain dir(), the method collects parameter information to the fullest extent
ITER () Used to generate an iterator
Next () Returns the next project for the iterator
Divmod () function combines the result of divisor and remainder operations to return a tuple (A//b, a% B) that contains the quotient and remainder. Divmod (7, 2)-> (3, 1)
ID () Used to get the memory address of an object
Sorted () Sort is the method that is applied on the list for all objects that can be iterated, and sorted can sort all the objects that can be iterated
Enumerate () Used to combine a data object that can be traversed (such as a list, tuple, or string) into an index sequence, listing data and data subscripts, typically used in a for loop
Open () Used to open a file Open (' Test.txt ')
Isinstance () To determine whether an object is a known type, similar to type (), Isinstance () considers a subclass to be a parent class type, considering an inheritance relationship
Type () Determines an object type and does not consider a subclass to be a parent class type, regardless of the inheritance relationship
SUM () To sum a series SUM ([0,1,2]), SUM ([0,1,2,3,4], 2)
Filter () Functions are used to filter sequences, filter out elements that are not eligible, and return a new list of qualified elements, filter (function, iterable) def IS_SQR (x): Return math.sqrt (x)% 1 = 0; NewList = filter (IS_SQR, Range (1, 101))
Issubclass () Determines whether the parameter class is a subclass of the type parameter ClassInfo, Issubclass (class, ClassInfo) Issubclass (B,a), B is a subclass of
Pow (x, y[, z]) The value of xy (Y-second side of X), if z is present, the result is modulo, and the result is equivalent to POW (x,y)%z,pow () is called directly from the built-in method, and the built-in method takes the argument as an integral type, and the Math module's POW () converts the argument to float
Super () A method used to invoke the parent class (superclass)
Format () Output Format function, the specific use of the method reference: Rookie Tutorial http://www.runoob.com/python/att-string-format.html
Len () Returns the length or number of items (characters, lists, tuples, etc.)
Range () The range (start, stop[, step) function returns an iterative object (type is an object), not a list type, so the list is not printed when printed Range (5)
Zip () Takes an object that can be iterated as a parameter, packs the corresponding elements in the object into a tuple, and then returns a list of those tuples. If the number of elements in each iterator is inconsistent, the return list is the same length as the shortest object, and the * operator allows you to extract the tuple into a list. Packaging: zipped = Zip (a,b), decompression: Zip (*zipped)
Map () Maps the specified sequence according to the provided function, map (function, iterable, ...), and the first parameter function calls the function function with each element in the parameter sequence, and returns a new list containing the return value of each of the function functions.
Round () Returns the rounding value of a floating-point number X
Hash () Used to get a hash of an object (a string or numeric value, etc.) Hash (' Test ')
Set () Create a unordered set of not repeating elements that you can test for relationships, delete duplicate data, and compute intersections, sets, and sets
Statement

The above content comes from the rookie tutorial

Related Article

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.