Python common functions early in the year big summary

Source: Internet
Author: User

1. Common built-in functions: (can be used directly without import)

Help (obj) online, obj is any type

Callable (obj) to see if an obj can be called like a function

Repr (obj) obtains a representation string of obj that can be used to reconstruct a copy of the object using the string eval

Eval_r (str) represents a valid Python expression that returns the expression

Dir (obj) to view the name visible in the name space of obj

Hasattr (obj,name) See if there is a name in the name space of obj

GetAttr (obj,name) gets a name in the name space of obj

SetAttr (Obj,name,value) is a name in the name space of obj pointing to Vale, the object

Delattr (obj,name) removes a name from the name space of obj

VARs (obj) returns the name space of an object. expressed in Dictionary

Locals () returns a local name space, denoted by dictionary

Globals () returns a global name space, denoted by dictionary

Type (obj) to view the types of an obj

Isinstance (OBJ,CLS) to see if obj is a CLS instance

Issubclass (subcls,supcls) View Subcls is not a subclass of Supcls

Type conversion function

Chr (i) to turn an ASCII value into a character

Ord (i) turns a character or Unicode character into an ASCII value

Oct (x) turns integer x into a string represented by octal

Hex (x) turns integer x into a hexadecimal-represented string

STR (obj) gets the string description of obj

List (seq) converts a sequence into a list

Tuple (seq) converts a sequence into a tuple

Dict (), Dict (list) converted to a dictionary

int (x) is converted to an integer

Long (x) converts to a long interger

Float (x) converted to a floating-point number

Complex (x) converted to plural

Max (...) to find the maximum value

Min (...) to find the minimum value

Built-in functions for executing programs

Complie If a piece of code is often used, it is faster to compile and then run.

2. Operating system-related calls

System-related Information module import sys

SYS.ARGV is a list that contains all the command-line arguments.

Sys.stdout Sys.stdin Sys.stderr respectively represents the standard input output, the error output of the file object.

Sys.stdin.readline () reads a line from the standard input sys.stdout.write ("a") screen output a

Sys.exit (Exit_code) Exit program

Sys.modules is a dictionary that represents all the available module in the system

Sys.platform getting running operating system environment

Sys.path is a list that indicates all paths to find Module,package.

Operating system-related calls and actions import OS

Os.environ A dictionary containing environment variables os.environ["Home" can get the value of the environment variable HOME

Os.chdir (dir) Change current directory Os.chdir (' D:\\outlook ') Note windows is used to escape

OS.GETCWD () Get current directory

Os.getegid () Gets the valid group ID Os.getgid () gets the group ID

Os.getuid () Get user ID Os.geteuid () get a valid user ID

Os.setegid Os.setegid () os.seteuid () Os.setuid ()

Os.getgruops () Get a list of user group names

Os.getlogin () get user login name

OS.GETENV Get Environment variables

OS.PUTENV Setting Environment variables

Os.umask setting Umask

Os.system (CMD) runs the cmd command with system calls

Examples of operations:

Os.mkdir ('/tmp/xx ') os.system ("Echo ' Hello ' >/tmp/xx/a.txt") os.listdir ('/tmp/xx ')

Os.rename ('/tmp/xx/a.txt ', '/tmp/xx/b.txt ') os.remove ('/tmp/xx/b.txt ') os.rmdir ('/tmp/xx ')

Write a simple shell in Python

#!/usr/bin/python

Import OS, sys

cmd = Sys.stdin.readline ()

While CMD:

Os.system (CMD)

cmd = Sys.stdin.readline ()

Writing platform-independent programs with Os.path

Os.path.abspath ("1.txt") = = Os.path.join (OS.GETCWD (), "1.txt")

Os.path.split (OS.GETCWD ()) is used to separate the directory part and the file name portion of a directory name.

Os.path.join (OS.GETCWD (), Os.pardir, ' a ', ' A.doc ') are all path names.

Os.pardir represents the character of the next-level directory on the current platform:

Os.path.getctime ("/root/1.txt") returns the CTime (creation time) timestamp of 1.txt

Os.path.exists (OS.GETCWD ()) to determine if a file exists

Os.path.expanduser (' ~/dir ') to extend the ~ to the user root directory

Os.path.expandvars (' $PATH ') Extended environment variable path

Os.path.isfile (OS.GETCWD ()) to determine if it is a file name, 1 is 0 no

Os.path.isdir (' c:\Python26\temp ') to determine if it is a directory, 1 is 0 no

Os.path.islink ('/home/huaying/111.sql ') is not available under symbolic connections under windows

Os.path.ismout (OS.GETCWD ()) is not available under the file system installation point under Windows

Os.path.samefile (OS.GETCWD (), '/home/huaying ') take a look at the two filenames that are not referring to the same file

Os.path.walk ('/home/huaying ', Test_fun, "A.C")

Traversing/home/huaying All subdirectories include this directory, and the function test_fun is called for each directory.

Example: In a directory, and all of his subdirectories look for names that are A.C files or directories.

def test_fun (filename, dirname, names)://filename is the walk a.c in DirName is the directory name that is accessed

If filename in names://names is a list that contains all the contents of the DirName directory

Print Os.path.join (dirname, filename)

Os.path.walk ('/home/huaying ', Test_fun, "A.C")

File operations

Open File

f = open ("FileName", "R") r read-only W writes RW read-write RB reading binary WB write binary w+ write append

Read and write files

F.write ("a") f.write (str) writes a string F.writeline () F.readlines () with the following read similar

F.read () all read out f.read (size) means reading a size character from a file

F.readline () reads a line to the end of the file, returning an empty string. F.readlines () reads all and returns a list. List each element represents a row that contains "\ n" \

F.tell () returns the current file read location

F.seek (off, where) locates the file read-write location. Off indicates an offset, a positive number moves toward the end of the file, and a negative indicates a move to the beginning.

Where is 0 means starting from the beginning, 1 means counting from the current position, and 2 means counting from the end.

F.flush () flush cache

Close File

F.close ()

Regular expression regular expressions import re

Simple RegExp.

p = re.compile ("abc") If P.match ("abc"): Print "Match"

In the above example, a pattern is generated first, and if it matches a string, a match object is returned

In addition to some special characters metacharacter metacharacters, most characters Nonalphanumeric and themselves match.

These special characters are. ^ $ * + ? { [ ] \ | ( )

Character set (denoted by [])

Lists characters, such as [ABC], that match A or B or C, and most metacharacter only represent and match itself in []. Cases:

A = ". ^$*+?" {\\| () "Most Metachar match itself in [], but" ^[]\ "differs

p = re.compile ("[" +a+ "]")

For I in A:

If P.match (i):

Print "[%s] is match"%i

Else

Print "[%s] is not match"%i

Include [] itself in [], which means "[" or "]" matches. denoted by \[and \].

^ appears at the beginning of [], indicating inversion. [^ABC] represents all characters except A,b,c. ^ does not appear at the beginning, that is, to match the body.

-can represent range. [A-za-z] matches any one of the English letters. [0-9] matches any number.

The magical magic in [].

\d [0-9]

\d [^0-9]

\s [\t\n\r\f\v]

\s [^ \t\n\r\f\v]

\w [a-za-z0-9_]

\w [^a-za-z0-9_]

\ t means match tab, and the other is consistent with the string notation

\x20 representation and hexadecimal ASCII 0x20 match

With \, any character can be represented in []. Note: A separate "." If [] does not appear, it indicates a match for any character other than \ n, similar to [^\n].

Repetition of RegExp

{M,n} indicates the presence of more than M (with M) and N (N). Matches such as Ab{1,3}c and ABC,ABBC,ABBBC do not match AC,ABBBC.

M is the Nether and n is the upper bound. The nether of token in M province is 0,n omitted and the upper bound of the table is infinitely large.

* indicates {,} + means {1,}? = {0,1}

The maximum and minimum matching python are the maximum matches, and if you want to minimize the match, add one after *,+,?, {m,n}.

The end of the match object can be used to match the position of the last character.

Re.compile ("A *"). Match (' AAAA '). End () 4 maximum match

Re.compile ("A *?"). Match (' AAAA '). End () 0 minimum match

Use raw string

The string representation method uses \ \ to represent characters \. Heavy usage affects readability.

Workaround: Add an R in front of the string to indicate the raw format.

A = r "\a" Print a result is \a

A = R "\" a "print a result is \" a

Using the RE module

First use Re.compile to get a regexobject to represent a regexp

After using the pattern of the Match,search method, get Matchobject

Then use match object to get the matching position, the matching string and other information

Regxobject commonly used functions:

>>> Re.compile ("a"). Match ("Abab") if Abab's beginning and Re.compile ("a") match, get Matchobject

<_sre. Sre_match Object at 0x81d43c8>

>>> Print Re.compile ("a"). Match ("Bbab")

None Note: Start matching from the beginning of Str

>>> Re.compile ("a"). Search ("Abab") searches for the first and re_obj matching sections in Abab

<_sre. Sre_match Object at 0x81d43c8>

>>> Print Re.compile ("a"). Search ("Bbab")

<_sre. Sre_match object at 0x8184e18> and match () do not have to match from the beginning

Re_obj.findall (str) returns STR to search for all and re_obj matching portions.

Returns a tuple in which the element is a matching string.

Common functions of Matchobject

M.start () returns to the starting position, M.end () returns the end position (the character that does not contain the position).

M.span () returns a tuple representation (M.start (), M.end ())

M.pos (), M.endpos (), M.re (), m.string ()

M.re (). Search (M.string (), M.pos (), M.endpos ()) will get m itself

M.finditer () can return a iterator that is used to traverse all found matchobject.

For M in Re.compile ("[AB]"). Finditer ("TATBXAXB"):

Print M.span ()

Advanced RegExp

| Represents the union of multiple RegExp. A b two X regexp,a| B means match A or match B.

^ indicates that only the beginning of a row is matched, ^ this special meaning is only at the beginning.

$ means only the end of a row is matched

\a to match only the beginning of the first line of the string ^ matches the beginning of each line

\z that matches only the end of a row line string matches the first line of the line end

\b Only matches the boundary example of a word: \binfo\b matches only "info" does not match information

\b to match non-word boundaries

Examples are as follows:

>>> Print Re.compile (r "\binfo\b"). Match ("info") #使用raw格式 \b Represents the word boundary

<_sre. Sre_match Object at 0x817aa98>

>>> print Re.compile ("\binfo\b"). Match ("info") #没有使用raw \b Represents the backspace number

None

>>> print Re.compile ("\binfo\b"). Match ("\binfo\b")

<_sre. Sre_match Object at 0x8174948>

Example Group (Group): Re.compile ("(A (b) c) d"). Match ("ABCD"). Groups (' abc ', ' B ')

#!/usr/local/bin/python

Import re

x = "" "

Name:charles

Address:bupt

Name:ann

Address:bupt

"""

#p = Re.compile (r "^name: (. *) \n^address: (. *) \ n", re. M

p = re.compile (r "^name: (? p<name>.*) \n^address: (? p<address>.*) \ n ", re. M

For M in P.finditer (x):

Print M.span ()

Print "Here is your friends list"

Print "%s,%s"%m.groups ()

Compile Flag

When using Re.compile to get regxobject, some flags can be used to adjust the detailed characteristics of the regxobject.

Dotall, S let. Match any character, including line break \ n

IGNORECASE, I ignore case

LOCALES, L let \w \w \b \b Be consistent with the current locale

MULTILINE, M Multi-line mode, only affects ^ and $ (see above example)

VERBOSE, X VERBOSE mode

Python common functions early in the year big summary

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.