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

>>> 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

In the following example we are sorted by the Tuple's 2nd and 3rd columns, and are in reverse order (reverse=true)

>>> 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 () to invoke system commands, The program cannot get output and return values >>> import os>>> os.system (' ls-l/proc/cpuinfo ') >>> os . system ("ls-l/proc/cpuinfo")-r--r--r--1 Root root 0 March 16:53/proc/cpuinfo 0 use Os.popen () to invoke the system command, the command output can be obtained in the program, but is unable to get execution return value >>> out = Os.popen ("ls-l/proc/cpuinfo") >>> print out.read ()-r--r--r--1 root root 0 March 2 9 16:59/proc/cpuinfo use Commands.getstatusoutput () to invoke the system command, the program can get the command output and execution of the return value >>> 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): the contents of the content of all written to the file, as is written, will not be reproduced in each line after the author QQ83075050


This article from "the Bird network" blog, declined reprint!

Summary of 12 basic knowledge commonly used in Python programming

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.