Python common functions and modules Z

Source: Internet
Author: User
Reprinted from pc10
Common functions

  • ABS (X)

    ABS () returns the absolute value of a number. If a plural number is given, the return value is the modulo of the plural number.

    >>>print abs(-100)
    100
    >>>print abs(1+2j)
    2.2360679775
  • Callable (object)

    The callable () function is used to test whether the object is callable. If yes, 1 (true) is returned; otherwise, 0 (false) is returned ). Callable objects include functions, methods, code objects, classes, and class instances that have defined the "call" method.

    >>> a="123"
    >>> print callable(a)
    0
    >>> print callable(chr)
    1
  • CMP (x, y)

    The CMP () function compares two objects, X and Y, and returns an integer based on the comparison result. If x <Y,-1 is returned. If x> Y, 1 is returned, if X = Y, 0 is returned.

    >>>a=1
    >>>b=2
    >>>c=2
    >>> print cmp(a,b)
    -1
    >>> print cmp(b,a)
    1
    >>> print cmp(b,c)
    0
  • Divmod (x, y)

    The divmod (x, y) function completes Division operations and returns the quotient and remainder.

    >>> divmod(10,3)
    (3, 1)
    >>> divmod(9,3)
    (3, 0)
  • Isinstance (object, class-or-type-or-tuple)-> bool

    Test Object Type

    >>> a='isinstance test'
    >>> b=1234
    >>> isinstance(a,str)
    True
    >>> isinstance(a,int)
    False
    >>> isinstance(b,str)
    False
    >>> isinstance(b,int)
    True
  • Len (object)-> integer

    The LEN () function returns the length of the string and sequence.

    >>> len("aa")
    2
    >>> len([1,2])
    2
  • Pow (X, Y [, Z])

    The POW () function returns the power of X as the base and Y as the index. If the Z value is given, this function calculates the y power value of X, which is the value of Z modulo.

    >>> print pow(2,4)
    16
    >>> print pow(2,4,2)
    0
    >>> print pow(2.4,3)
    13.824
  • Range ([lower,] Stop [, step])

    The range () function generates a list of sequential integers based on parameters.

    >>> range(10)
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> range(1,10)
    [1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> range(1,10,2)
    [1, 3, 5, 7, 9]
  • Round (X [, N])

    The round () function returns the rounding value of floating point X. If n is given, it indicates the number of digits rounded to the decimal point.

    >>> round(3.333)
    3.0
    >>> round(3)
    3.0
    >>> round(5.9)
    6.0
  • Type (OBJ)

    The type () function returns the data type of an object.

    >>> type(a)
    <type 'list'>
    >>> type(copy)
    <type 'module'>
    >>> type(1)
    <type 'int'>
  • Xrange ([lower,] Stop [, step])

    The xrange () function is similar to range (), but xrnage () does not create a list, but returns an xrange object. Its behavior is similar to the list, however, the list value is calculated only when needed. when the list is large, this feature can save us memory.

    >>> a=xrange(10)
    >>> print a[0]
    0
    >>> print a[1]
    1
    >>> print a[2]
    2
Built-in type conversion functions
  • CHR (I)

    The CHR () function returns the string corresponding to the ASCII code.

    >>> print chr(65)
    A
    >>> print chr(66)
    B
    >>> print chr(65)+chr(66)
    AB
  • Complex (real [, imaginary])

    The complex () function converts a string or number to a plural number.

    >>> complex("2+1j")
    (2+1j)
    >>> complex("2")
    (2+0j)
    >>> complex(2,1)
    (2+1j)
    >>> complex(2L,1)
    (2+1j)
  • Float (X)

    The float () function converts a number or string to a floating point number.

    >>> float("12")
    12.0
    >>> float(12L)
    12.0
    >>> float(12.2)
    12.199999999999999
  • Hex (X)

    The hex () function converts an integer to a hexadecimal number.

    >>> hex(16)
    '0x10'
    >>> hex(123)
    '0x7b'
  • Long (X [, base])

    The long () function converts numbers and strings into integers, and the base is an optional base.

    >>> long("123")
    123L
    >>> long(11)
    11L
  • List (X)

    The List () function converts a sequence object to a list. For example:

    >>> list("hello world")
    ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
    >>> list((1,2,3,4))
    [1, 2, 3, 4]
  • INT (X [, base])

    The int () function converts numbers and strings into an integer. Base is the optional base.

    >>> int(3.3)
    3
    >>> int(3L)
    3
    >>> int("13")
    13
    >>> int("14",15)
    19
  • Min (X [, Y, Z...])

    The min () function returns the minimum value of a given parameter, which can be a sequence.

    >>> min(1,2,3,4)
    1
    >>> min((1,2,3),(2,3,4))
    (1, 2, 3)
  • Max (X [, Y, Z...])

    The max () function returns the maximum value of a given parameter, which can be a sequence.

    >>> max(1,2,3,4)
    4
    >>> max((1,2,3),(2,3,4))
    (2, 3, 4)
  • Oct (X)

    The OCT () function converts an integer to an octal number.

    >>> oct(8)
    '010'
    >>> oct(123)
    '0173'
  • Ord (X)

    The ord () function returns the ASCII or Unicode value of a string parameter.

    >>> ord("a")
    97
    >>> ord(u"a")
    97
  • STR (OBJ)

    The STR () function converts an object to a printable string.

    >>> str("4")
    '4'
    >>> str(4)
    '4'
    >>> str(3+2j)
    '(3+2j)'
  • Tuple (X)

    The tuple () function converts a sequence object to a tuple.

    >>> tuple("hello world")
    ('h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd')
    >>> tuple([1,2,3,4])
    (1, 2, 3, 4)
  • Sequence processing functions
  • Len (), max (), and min () in common functions can also be used for sequences.

  • Filter (function, list)

    When filter () is called, it applies a function to each item in the sequence, and returns all items in the return value of the function to the true value, so as to filter out all items that return the false value.

    >>> def nobad(s):
    ... return s.find("bad") == -1
    ...
    >>> s = ["bad","good","bade","we"]
    >>> filter(nobad,s)
    ['good', 'we']

    In this example, the nobad () function is applied to all items in the S sequence to filter out all items containing "bad.

  • Map (function, list [, list])

    The map () function applies a function to all items in the sequence and returns a list.

    >>> import string
    >>> s=["python","zope","linux"]
    >>> map(string.capitalize,s)
    ['Python', 'Zope', 'Linux']

    Map () can also be applied to multiple lists at the same time. For example:

    >>> import operator
    >>> s=[1,2,3]; t=[3,2,1]
    >>> map(operator.mul,s,t) # s[i]*t[j]
    [3, 4, 3]

    If a none value is passed, instead of a function, map () merges the corresponding elements in each sequence and returns the tuples. For example:

    >>> a=[1,2];b=[3,4];c=[5,6]
    >>> map(None,a,b,c)
    [(1, 3, 5), (2, 4, 6)]
  • Reduce (function, seq [, init])

    The reduce () function obtains the first two items in the sequence and passes them to the provided function. After obtaining the result, it obtains the next item in the sequence, passes the result to the function, and so on, until all items are processed.

    >>> import operator
    >>> reduce(operator.mul,[2,3,4,5]) # ((2*3)*4)*5
    120
    >>> reduce(operator.mul,[2,3,4,5],1) # (((1*2)*3)*4)*5
    120
    >>> reduce(operator.mul,[2,3,4,5],2) # (((2*2)*3)*4)*5
    240
  • Zip (SEQ [, seq,...])

    The zip () function combines the corresponding items in two or more sequences, returns them in the format of tuples, and stops processing all the items in the shortest sequence.

    >>> zip([1,2,3],[4,5],[7,8,9])
    [(1, 4, 7), (2, 5, 8)]

    If the parameter is a sequence, zip () returns each item in the format of a mona1 group, for example:

    >>> zip((1,2,3,4,5))
    [(1,), (2,), (3,), (4,), (5,)]
    >>> zip([1,2,3,4,5])
    [(1,), (2,), (3,), (4,), (5,)]

The module can separate a complex program and store it in different files by function, making it easier to maintain and manage the program. The module in python is a Python code file ending with. py. You can run the import command, for example:

import sys

Import completes the following three operations:

  • Create a new namespace that contains all objects defined in the input module;

  • Code in the execution module;

  • Name of the variable that creates the namespace.

The import statement can be used to input multiple modules at the same time, for example:

import os,sys,system

It can also be written as follows:

import os
import sys
import system

Some modules have a long name, so we can give it a simple alias when entering it, which makes it much easier to use the objects in the module, such:

import ftplib as ftp

Sometimes we only want to use an object in the module, and do not want to input the entire module, we can use the from... Import Statement to input a specific object. For example:

from ftplib import FTP

In this way, we can directly use FTP () without a prefix.

If an error occurs in the module, an importerror exception is thrown. We can capture the exception and handle it accordingly.

Python scripts and modules are all files ended with. py. How does the program determine whether a. py file is used as a script or a module? The key is a variable named _ name _. If its value is _ main __, it cannot be used as a module and can only be run directly as a script. Therefore, at the end of many scripts, there is a statement similar to the following. The limit can only be run in script mode, not as a module:

if __name__ == '__main__':
main()

Several modules with similar functions can form a python package, store it in a directory structure, and call objects through the input package path. To define a package, you need to create a directory with the same name as the package name, and create the _ init _. py file under the directory. This file is the package initialization file. It can be empty or define a code. For example, the Directory of A webdesign package is as follows:

/WebDesign
__init_.py
design.py
draw.py
...

You can enter the design module using the following statement:

import WebDesign.design
String Module
  • Replace (string, old, new [, maxsplit])

    String replacement function to replace the old value in the string with new. By default, all old values in the string are replaced with the new value. If the maxsplit value is given, you can also control the number of replicas. If the maxsplit value is 1, only the first old value is replaced.

    >>>a="11223344"
    >>>print string.replace(a,"1","one")
    oneone2223344
    >>>print string.replace(a,"1","one",1)
    one12223344
  • Capitalize (string)

    This function can replace the first character of a string with a letter.

    >>> import string
    >>> print string.capitalize("python")
    Python
  • Split (string, SEP = none, maxsplit =-1)

    Returns a list from a string, with the SEP value as the delimiter.

    >>> import string
    >>> ip="192.168.3.3"
    >>> ip_list=string.split(ip,'.')
    >>> print ip_list
    ['192', '168', '3', '3']
  • Join (string [, SEP])

    Returns the string connected with SEP. The default SEP is a space.

    >>> import string
    >>> a = ['a','b','c']
    >>> b = string.join(a,'-')
    >>> b
    'a-b-c'
    >>> a
    ['a', 'b', 'c']
Time Module

The built-in module time contains many time-related functions. We can use it to obtain the current time and format the time output.

  • Time (), returns the number of seconds since the Linux New Century in the form of floating point. In Linux, 00:00:00 UTC, January 1, 1970 are the beginning of a new era.

    >>> time.time()
    1150269086.6630149
    >>> time.ctime(1150269086.6630149)
    >>> 'Wed Jun 14 15:11:26 2006'
  • Ctime ([SEC]) converts the number of seconds to the date format. If no parameter is included, the current time is displayed.

    >>> import time
    >>> time.ctime()
    >>> 'Wed Jun 14 15:02:50 2006'
    >>> time.ctime(1138068452427683)
    'Sat Dec 14 04:51:44 1901'
  • Sleep (SECs), timing.

    >>> Time. Sleep (10)
    >>># It will appear 10 seconds later >>> prompt
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.