Python functions and common modules

Source: Internet
Author: User
This article introduces python functions and common modules in detail.
  • Recursion

  • Reflection

  • OS module

  • Sys module

  • Hashlib encryption module

  • Regular expression

Reflection

The reflection function in python is provided by the following four built-in functions: hasattr, getattr, setattr, and delattr. The four functions are used to internally execute the object respectively: check whether a member is contained, a member is obtained, a member is set, and a member is deleted.

Class Foo (object): def init (self): self. name = 'wupeiqi 'def func (self): return 'func' obj = Foo () #### check whether a member is contained #### hasattr (obj, 'name') hasattr (obj, 'func') #### obtain a member ### getattr (obj, 'name') getattr (obj, 'func ') ##### set members #### setattr (obj, 'age', 18) setattr (obj, 'show ', lambda num: num + 1) ##### delete a member #### delattr (obj, 'name') delattr (obj, 'func ')
OS module
OS. getcwd () # obtain the current working directory, that is, the operating directory path of the current python script, OS. chdir ("dirname") # Change the current script working directory, which is equivalent to cdos in shell. curdir # returns the current directory :('. ') OS. pardir # obtain the string name of the parent directory of the current directory :('.. ') OS. makedirs ('dir1/dir2') # multiple-layer Recursive directory OS can be generated. removedirs ('dirname1') # if the directory is empty, delete it and recursively go to the upper-level Directory. if the directory is empty, delete it and push OS accordingly. mkdir ('dirname') # generate a single-level directory, which is equivalent to mkdir dirnameos in shell. rmdir ('dirname') # delete a single-stage empty directory. if the directory is not empty, it cannot be deleted. an error is returned, which is equivalent to rmdir dirnameos in shell. listdir ('dirname') # List all files and subdirectories under the specified directory, package Contains hidden files and prints OS in list mode. remove () # delete a file OS. rename ("oldname", "new") # rename the file/directory OS. stat ('path/filename ') # obtain the file/directory information OS. sep # specifies the path delimiter of the operating system. In win, it is "\", and in Linux it is "/" OS. linesep # The line terminator used by the current platform. in win, it is \ t \ n, and in Linux it is \ n OS. pathsep # string OS used to split the file path. name # string indicates the current platform. Win-> 'nt '; Linux-> 'posix' OS. system ("bash command") # run the shell command to directly display the OS. environ # obtain the OS environment variable. path. abspath (path) # returns the absolute path OS of path normalization. path. split (path) # split the path into two groups of directories and file names and return the OS. path. dirname (path) # returns the path directory. The first element of OS. path. split (path) is OS. path. basename (path. If the path ends with a slash (/) or slash (\), a null value is returned. That is, OS. path. the second element of split (path), OS. path. exists (path) # True is returned if path exists. If path does not exist, Falseos is returned. path. isabs (path) # If path is an absolute path, Trueos is returned. path. isfile (path) # If path is an existing file, True is returned. Otherwise, Falseos. path. isdir (path) # returns True if path is an existing directory. Otherwise, Falseos is returned. path. join (path1 [, path2 [,...]) # If multiple paths are combined, the parameters before the first absolute path are ignored. path. getatime (path) # returns the last access time OS of the file or directory pointed to by path. path. getmtime (path) # return the last modification time of the file or directory pointed to by path. sys module
Sys module
Sys. argv # List of command line parameters. The first element is the program path sys. exit (n) # exit the program. exit (0) sys when the program exits normally. version # obtain the version information of the Python program sys. maxint # The maximum Int value sys. path # return the module's search path. during initialization, use the PYTHONPATH environment variable value sys. platform # return the name of the operating system platform sys. stdin # Input related sys. stdout # output related sys. stderror # Error
Hashlib encryption module

Used for encryption-related operations, instead of the md5 module and sha module, mainly provides SHA1, sha1_, SHA256, SHA384, SHA512, MD5 algorithm

import hashlib # ######## md5 ######## hash = hashlib.md5()hash.update('admin')print hash.hexdigest() # ######## sha1 ######## hash = hashlib.sha1()hash.update('admin')print hash.hexdigest() # ######## sha256 ######## hash = hashlib.sha256()hash.update('admin')print hash.hexdigest()  # ######## sha384 ######## hash = hashlib.sha384()hash.update('admin')print hash.hexdigest() # ######## sha512 ######## hash = hashlib.sha512()hash.update('admin')print hash.hexdigest()

Although the above encryption algorithms are still very powerful, they have some drawbacks, that is, they can be reversed by credential stuffing. Therefore, it is necessary to add a custom key to the encryption algorithm and then encrypt it.

import hashlib # ######## md5 ######## hash = hashlib.md5('898oaFs09f')hash.update('admin')print hash.hexdigest()

Not enough? Python also has an hmac module, which internally processes and encrypts the key and content.

import hmach = hmac.new('wueiqi')h.update('hellowo')print h.hexdigest()

No more !!!

Import hashlibobj = hashlib. md5 () obj. update (bytes ('admin', encoding = 'utf-8') result = obj. hexdigest () print (result) # add the key obj = hashlib. md5 (bytes ('xxxxxxxx', encoding = 'utf-8') obj. update (bytes ('admin', encoding = 'utf-8') result = obj. hexdigest () print (result)

Regular expression

The re module is used to operate python regular expressions.

Character:

. Match any character except linefeed
\ W matches letters, numbers, underscores, and Chinese characters
\ S matches any blank space character
\ D matching number
\ B matches the start or end of a word
^ Match the start of a string
$ End of matching string

Times:

* Repeated zero or more times
+ Repeat once or more times
? Zero or one repetition
{N} repeated n times
{N,} repeat n times or more times
{N, m} repeat n to m times

IP: ^ (25 [0-5] | 2 [0-4] \ d | [0-1]? \ D? \ D) (\. (25 [0-5] | 2 [0-4] \ d | [0-1]? \ D? \ D) {3} $ mobile phone number: ^ 1 [3 | 4 | 5 | 8] [0-9] \ d {8} $

1. match (pattern, string, flags = 0)

Match the specified content in the string according to the model from the starting position to match a single

  • Regular expression

  • String to be matched

  • Flag, used to control the matching mode of regular expressions

import reobj = re.match('\d+', '123uuasf')if obj:    print obj.group()

2. search (pattern, string, flags = 0)

Match the specified content in the string according to the model and match a single

import reobj = re.search('\d+', 'u123uu888asf')if obj:    print obj.group()

3. group and groups

a = "123abc456"print re.search("([0-9]*)([a-z]*)([0-9]*)", a).group()print re.search("([0-9]*)([a-z]*)([0-9]*)", a).group(0)print re.search("([0-9]*)([a-z]*)([0-9]*)", a).group(1)print re.search("([0-9]*)([a-z]*)([0-9]*)", a).group(2)print re.search("([0-9]*)([a-z]*)([0-9]*)", a).groups()

4. findall (pattern, string, flags = 0)

The above two methods are used to match a single value, that is, only one of the strings can be matched. if you want to match all the elements that meet the conditions in the string, you need to use findall.

import reobj = re.findall('\d+', 'fa123uu888asf')print obj

5. sub (pattern, repl, string, count = 0, flags = 0)

Used to replace matched strings

content = "123abc456"new_content = re.sub('\d+', 'sb', content)# new_content = re.sub('\d+', 'sb', content, 1)print new_content

More powerful than str. replace

6. split (pattern, string, maxsplit = 0, flags = 0)

Grouping based on specified matches

content = "'1 - 2 * ((60-30+1*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2) )'"new_content = re.split('\*', content)# new_content = re.split('\*', content, 1)print new_content
content = "'1 - 2 * ((60-30+1*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2) )'"new_content = re.split('[\+\-\*\/]+', content)# new_content = re.split('\*', content, 1)print new_content
inpp = '1-2*((60-30 +(-40-5)*(9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2))'inpp = re.sub('\s*','',inpp)new_content = re.split('\(([\+\-\*\/]?\d+[\+\-\*\/]?\d+){1}\)', inpp, 1)print new_content

More powerful than str. split

The above is a detailed description of python functions and common modules. For more information, see other related articles in the first PHP community!

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.