A summary of 12 basic knowledge points in Python language

Source: Internet
Author: User
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
Copy the Code code as follows:

>>> 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
Copy the Code code as follows:

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)
Copy the Code code as follows:

>>> 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 ', 6429600, ' 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
Copy the Code code as follows:

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

Copy the Code code as follows:

>>> 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 ')]

6, dictionary, list, String mutual transfer

The following is the build database connection string, converting from dictionary to string
Copy the Code code as follows:

>>> 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
Copy CodeThe code is as follows:

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

Converting a time object into a string
Copy the Code code as follows:

>>> Import datetime
>>> Datetime.datetime.now (). Strftime ("%y-%m-%d%h:%m")
' 2011-01-20 14:05 '


Time-size comparison
Copy CodeThe code is as follows:

>>> 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
Copy CodeThe code is as follows:

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


Convert a string into a time object
Copy CodeThe code is as follows:

>>> endtime=datetime.datetime.strptime (' 20100701 ', "%y%m%d")
>>> type (endtime)

>>> Print Endtime
2010-07-01 00:00:00


The number of seconds from 1970-01-01 00:00:00 UTC to the present, formatted output
Copy CodeThe code is as follows:


>>> 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 when you write some day operations scripts, you need to enter different command-line options to implement different functions according to different conditions.
The getopt module in Python provides a good way to implement the parsing of command-line parameters, the following distance description. Please see the following procedure:
Copy the Code code as follows:

#!/usr/bin/env python
#-*-Coding:utf-8-*-
Import sys,os,getopt
def usage ():
Print ""
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 Info
Test.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"% arg
elif opt = = '-F ':
Print "read file%s"% arg
elif opt = = '-C ':
Print "user-defined%s"% arg
elif opt = = '-E ':
Print "Exchange Name%s"% arg
elif opt = = '-S ':
Print "Stock code%s"% arg
elif 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 a string
Copy the Code code as follows:

>>> str= "ABCDEFG"
>>> print "%.3s"% str
Abc


Output by fixed width, insufficient to use space completion, the following example output width of 10
Copy CodeThe code is as follows:

>>> str= "ABCDEFG"
>>> print "%10s"% str
Abcdefg


Truncate string, output by fixed width
Copy CodeThe code is as follows:

>>> str= "ABCDEFG"
>>> print "%10.3s"% str
Abc


Floating-point type data bits reserved
Copy CodeThe code is as follows:

>>> Import Fpformat
>>> a= 0.0030000000005
>>> B=fpformat.fix (a,6)
>>> Print B
0.003000


Rounding of floating-point numbers, mainly using the round function
Copy CodeThe code is as follows:

>>> 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/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 Decimal
Copy the Code code as follows:

>>> 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 output and return values cannot be obtained in the program
Copy the Code code as follows:

>>> 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 cannot get the return value of execution
Copy CodeThe code is as follows:

>>> out = Os.popen ("Ls-l/proc/cpuinfo")
>>> Print Out.read ()
-r--r--r--1 root root 0 March 16:59/proc/cpuinfo


Using Commands.getstatusoutput () to invoke system commands, you can get the return value of command output and execution in the program
Copy CodeThe code is as follows:

>>> 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
Copy the Code code as follows:

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

Read the file into the list at once, the speed is faster, the application file is relatively small case
Copy the Code code as follows:

Track_file = "Track_stock.conf"
FD = open (Track_file)
Content_list = Fd.readlines ()
Fd.close ()
For line in Content_list:
Print Line


Progressive read-In, slow, suitable for not enough memory to read the entire file (file too Large)
Copy CodeThe code is as follows:

FD = open (File_path)
Fd.seek (0)
title = Fd.readline ()
Keyword = fd.readline ()
UUID = Fd.readline ()
Fd.close ()

The difference between writing a file 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 into a file, write it as-is, and not add anything behind each line

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