12 basic knowledge summaries commonly used in Python programming

Source: Internet
Author: User
Tags print format readline

12 basic knowledge commonly used in Python programming: Regular expression substitution, traversal of directory methods, list sorting by column, de-weight, dictionary ordering, dictionary, list, string reciprocal, time object manipulation, command-line argument parsing (getopt), print format output, binary conversion, Python calls system commands or scripts, and Python reads and writes files.

1. Regular expression substitution

Target: Replace Overview.gif in string line with other strings

>>> line = '  >>> mo=re.compile (R ' (? <=src=) "([\w+\.] +) "', Re. I) >>> mo.sub (R ' "\1****" ', line) '  >>> mo.sub (R ' Replace_ Str_\1 ', line) '  ' </span> >>> mo.sub (R ' " Testetstset "', line) ' 

Note: Where \1 is the data that is matched to, you can refer directly to it in such a way

2. Traverse Directory method

At some point, we need to traverse a directory to find a specific list of files that can be traversed by the Os.walk method, which is very convenient
Import OS
FileList = []
RootDir = "/data"
For root, subfolders, files in Os.walk (RootDir):
If '. SVN ' in SubFolders:subFolders.remove ('. SVN ') # Exclude specific directories
For file in Files:
If File.find (". t2t")! = -1:# Find a file with a specific extension
File_dir_path = Os.path.join (root,file)
Filelist.append (File_dir_path)
Print FileList

3. List sorted by columns (list sort)

If each element of the list is a tuple (tuple), and we want to sort by a column of tuples, refer to the following method

>>> a = [(' 2011-03-17 ', ' 2.26 ', 6429600, ' 0.0 '), (' 2011-03-16 ', ' 2.26 ', 12036900, '-3.0 '), (' 2011-03-15 ', ' 2.33 ', 15615500, ' -19.1 ')]>>> print a[0][0]2011-03-17>>> B = Sorted (A, Key=lambda result:result[1],reverse= True) >>> print b[(' 2011-03-15 ', ' 2.33 ', 15615500, ' 19.1 '), (' 2011-03-17 ', ' 2.26 ', 6429600, ' 0.0 '), (' 2011-03-16 ', ' 2.26 ', 12036900, ' -3.0 ')]>>> C = Sorted (A, Key=lambda result:result[2],reverse=true) >> > Print c[(' 2011-03-15 ', ' 2.33 ', 15615500, '-19.1 '), (' 2011-03-16 ', ' 2.26 ', 12036900, '-3.0 '), (' 2011-03-17 ', ' 2.26 ', 6 429600, ' 0.0 ')]
4, list to go to heavy (lists Uniq)

Sometimes you need to delete the duplicate elements in the list by using the following method

>>> lst= [(1, ' SSS '), (2, ' fsdf '), (1, ' SSS '), (3, ' fd ')]>>> set (LST) set ([(2, ' fsdf '), (3, ' fd '), (1, ' SSS ') )] >>>>>> lst = [1, 1, 3, 4, 4, 5, 6, 7, 6]>>> set (LST) set ([1, 3, 4, 5, 6, 7])
5. Dictionary sort (dict sort)

In general, we sort by the dictionary key, but if we want to sort by the value of the dictionary, we use the following method

>>> from operator import itemgetter>>> AA = {"A": "1", "SSS": "2", "FFDF": ' 5 ', "ffff2": ' 3 '}>>> Sort_aa = sorted (Aa.items (), Key=itemgetter (1)) >>> sort_aa[(' A ', ' 1 '), (' SSS ', ' 2 '), (' Ffff2 ', ' 3 '), (' Ffdf ', ' 5 ‘)]

From the running results above, the value of the dictionary is sorted according to the

6, dictionary, list, String mutual transfer

The following is the build database connection string, converting from dictionary to string

>>> params = {"Server": "Mpilgrim", "Database": "Master", "UID": "sa", "pwd": "Secret"}>>> ["%s=%s"% (K, V) for K, V in Params.items () [' Server=mpilgrim ', ' uid=sa ', ' database=master ', ' Pwd=secret ']>>> ";". Join (["%s=%s"% (k, v) for K, V in Params.items ()]) ' Server=mpilgrim;uid=sa;database=master;pwd=secret '

The following example converts a string into a dictionary

>>> a = ' server=mpilgrim;uid=sa;database=master;pwd=secret ' >>> AA = {}>>> for i in A.split ('; ') ): aa[i.split (' = ', 1) [0]] = i.split (' = ', 1) [1]...>>> aa{' pwd ': ' Secret ', ' database ': ' Master ', ' uid ': ' sa ', ' Server ': ' Mpilgrim '}
7. Time Object operation
Converts a time object to a string >>> import datetime>>> datetime.datetime.now (). Strftime ("%Y-%m-%d  %h:%m ")    ' 2011-01-20 14:05 '   time-size comparison >>> import time>>>  t1 = time.strptime (' 2011-01-20 14:05 ', "%y-%m-%d %h:%m") >>> t2 =  time.strptime (' 2011-01-20 16:05 ', "%y-%m-%d %h:%m") >>> t1 > t2   False>>> t1 < t2  True  time difference calculation, calculated 8 hours ago >>>  Datetime.datetime.now (). Strftime ("%y-%m-%d %h:%m")    ' 2011-01-20 15:02 ' >>>  ( Datetime.datetime.now ()  - datetime.timedelta (hours=8)). Strftime ("%y-%m-%d %h:%m")    ' 2011-01-20 07:03 '   Converts a string into a Time object >>> endtime=datetime.datetime.strptime (' 20100701 ', "%Y%m%d ") >>> type (endtime)   <type  ' Datetime.datetime ' >>>> print  endtime  2010-07-01 00:00:00  the number of seconds from  1970-01-01 00:00:00 UTC  to now, formatted output    > >> import time>>> a = 1302153828>>> time.strftime ("%Y-% M-%d %h:%m:%s ", Time.localtime (a))    ' 2011-04-07 13:23:48 '
8, command-line parameter parsing (getopt)

Usually in the writing of some of the day operation of the script, you need to enter different command line options according to different conditions to achieve different functions in Python provides the getopt module good implementation of the command line parameter parsing, the following distance description. Please see the following procedure:

#!/usr/bin/env python# -*- coding: utf-8 -*-import sys,os,getoptdef usage () :p rint  "Usage: analyse_stock.py [options ...] options:-e : exchange name-c : user-defined category name-f :  read stock info from file and save to db-d : delete  from db by stock code-n : stock name-s : stock code-h :  this help infotest.py -s haha -n  "Ha ha"  try:opts, args  = getopt.getopt (sys.argv[1:], ' he:c:f:d:n:s: ') except getopt. Getopterror:usage () Sys.exit () If len (opts)  == 0:usage () sys.exit ()   for opt,  arg in opts:if opt in  ('-H ',  '--help '):   usage ()   sys.exit () elif opt ==  '-d ':  print  "del stock %s"  % argelif opt ==  '-F ':  print  "read file %s"  % argelif opt  ==  '-C ':  print  "user-defined %s "  % argelif opt ==  '-E ':  print  ' exchange name %s '  % argelif opt ==  '-s ':   print  "stock code %s"  % argelif opt ==  '-n ':   print   "stock name %s"  % arg  sys.exit ()
9. Print formatted output 9.1, formatted output string
To intercept the string output, the following example will only output the first 3 letters of the string >>> str= "ABCDEFG" >>> print  "%.3s"  % str &NBSP;&NBSP;ABC by fixed width output, insufficient use of space completion, the following example output width of 10>>> str= "ABCDEFG" >>> print  "%10s" &NBSP;%&NBSP;STR&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;ABCDEFG intercept string, output >>> str= "ABCDEFG" according to fixed width >>>  print  "%10.3s"  % str         abc floating-point type data bits reserved >>> import fpformat>>> a= 0.0030000000005>>> b= Fpformat.fix (a,6) >>> print b  0.003000 A floating-point number rounding, mainly using the round function >>> from  decimal import *>>> a = "2.26" >>> b = "2.29" >>>  c = decimal (a)  - decimal (b) >>> print c  -0.03>> > c / decimal (a)  * 100  decimal (' -1.327433628318584070796460177 ') > >> decimal (Str (Round (c&Nbsp;/ decimal (a)  * 100, 2))   decimal ('-1.33 ') 
9.2. Binary conversion

There are times when you need to make a different conversion, you can refer to the following example (%x 16,%d decimal,%o Octal

>>> num = 10>>> print "hex =%x,dec =%d,oct =%o"% (num,num,num) Hex = A,dec = 10,oct = 12
10. Python calls system commands or scripts
 using  os.system ()   Calling system commands  ,  unable to get output and return values in the program >>> import os>>>  Os.system (' Ls -l /proc/cpuinfo ') >>> os.system ("Ls -l /proc/cpuinfo")    -r--r--r-- 1 root root 0  3 Month  29 16:53 /proc/cpuinfo   0  use  os.popen ()   Call system commands to get command output in,  program, but cannot get the return value of execution >>> out =  Os.popen ("Ls -l /proc/cpuinfo") >>> print out.read ()   -r--r--r-- 1  root root 0  3 Month  29 16:59 /proc/cpuinfo   use   Commands.getstatusoutput ()   Call system command,  the return value of command output and execution can be obtained in the program >>> import commands>> > commands.getstatusoutput (' Ls /bin/ls ')    (0,  '/bin/ls ') 
11, Python capture user Ctrl + C, Ctrl+d event

Sometimes, you need to capture user keyboard events in the program, such as CTRL + C exit, so that you can better safely exit the program
Try
Do_some_func ()
Except Keyboardinterrupt:
Print "User Press ctrl+c,exit"
Except Eoferror:
Print "User Press ctrl+d,exit"

12. Python Read and write files
One-time read into the file to the list, faster, suitable for the file is relatively small case track_file = "track_stock.conf" FD = open (track_file) content_list = Fd.readlines () fd.close () for lines in Content_list:print line read-through, slow, not enough memory to read the entire file (file too Large) fd = open (file_path) fd.seek (0) title = Fd.readline () keyword = fd.readline () uuid = Fd.readline () fd.close () writes the difference between write and Writelines Fd.write (str): Writes STR to a file, write () does not Add a newline character after Str fd.writelines (content): Write all contents to the file, write it as-is, and not add anything behind each line


12 basic knowledge summaries commonly used in Python programming

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.