12 basic knowledge points of the Python language, python Summary

Source: Internet
Author: User

12 basic knowledge points of the Python language, python Summary

12 basic knowledge commonly used in python programming: Regular Expression replacement, Directory Traversal method, list sorting by column, deduplication, Dictionary sorting, Dictionary, list, String Conversion, time object operations, Command Line Parameter Parsing (getopt), print format output, hexadecimal conversion, Python calls system commands or scripts, and Python reads and writes files.

1. Regular Expression replacement

Purpose: To replace overview.gif in the string line with other strings.
Copy codeThe Code is 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: \ 1 is the matched data, which can be directly referenced in this way.

2. Directory Traversal

In some cases, we need to traverse a directory to find a specific file list, which can be traversed through the OS. walk method, which is very convenient.
Copy codeThe Code is as follows: import OS
FileList = []
Rootdir = "/data"
For root, subFolders, files in OS. walk (rootdir ):
If '. svn' in subFolders: subFolders. remove ('. svn') # exclude a specific directory
For file in files:
If file. find (". t2t ")! =-1: # search for files with a specific extension
File_dir_path = OS. path. join (root, file)
FileList. append (file_dir_path)

Print fileList

3. sort the list by column (list sort)

If each element in the list is a tuple, we want to sort it according to a column of the tuples. refer to the following method.
In the following example, we sort the data in the 2nd and 3rd columns of the tuples in reverse order (reverse = True)
Copy codeThe Code is as follows: >>> a = [('2017-03-17 ', '2. 26 ', 6429600, '0. 0'), ('2017-03-16 ', '2. 26', 12036900, '-3.0 '),
('2014-03-15 ', '2. 33', 2011,'-15615500 ')]
>>> Print a [0] [0]
2011-03-17
>>> B = sorted (a, key = lambda result: result [1], reverse = True)
>>> Print B
[('2014-03-15 ', '2. 33 ', 15615500,'-19.1 '), ('2017-03-17', '2. 26 ', 6429600, '0. 0 '),
('1970-03-16 ', '2. 26', 2011,'-12036900 ')]
>>> C = sorted (a, key = lambda result: result [2], reverse = True)
>>> Print c
[('2014-03-15 ', '2. 33 ', 15615500,'-19.1 '), ('2017-03-16', '2. 26', 12036900, '-3.0 '),
('1970-03-17 ', '2. 26', 2011, '0. 0')]

4. list deduplication (list uniq)

To delete repeated elements in the list, use the following method:
Copy codeThe Code is as follows: >>> lst = [(1, 'ss'), (2, 'fsdf '), (1, 'ss'), (3, 'fd ')]
>>> Set (lst)
Set ([(2, 'fsdf '), (3, 'fd'), (1, 'ss')])
>>>
>>> Lst = [1, 1, 3, 4, 4, 5, 6, 7, 6]
>>> Set (lst)
Set ([1, 3, 4, 5, 6, 7])

5. dictionary sorting (dict sort)

Generally, we sort the keys of the dictionary. However, if we want to sort the keys of the dictionary, we use the following method:

Copy codeThe Code is 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'), ('ss', '2'), ('ffff2', '3'), ('ffdf ', '5')]

6. dictionary, list, and String Conversion

The following describes how to generate a database connection string and convert it from dictionary to string.
Copy codeThe Code is 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. split (';'): aa [I. split ('=', 1) [0] = I. split ('=', 1) [1]
...
>>> Aa
{'Pwd': 'secret', 'database': 'master', 'uid': 'sa ', 'server': 'mpilgrim '}

7. Time object operations

Converts a time object to a string.
Copy codeThe Code is as follows: >>> import datetime
>>> Datetime. datetime. now (). strftime ("% Y-% m-% d % H: % M ")
'2017-01-20'

Time size comparison
Copy codeThe Code is as follows: >>> import time
>>> T1 = time. strptime ('2017-01-20 ', "% Y-% m-% d % H: % M ")
>>> T2 = time. strptime ('2017-01-20 ', "% Y-% m-% d % H: % M ")
>>> T1> t2
False
>>> T1 <t2
True

Calculate the time difference, calculated 8 hours ago
Copy codeThe Code is as follows: >>> datetime. datetime. now (). strftime ("% Y-% m-% d % H: % M ")
'2017-01-20'
>>> (Datetime. datetime. now ()-datetime. timedelta (hours = 8). strftime ("% Y-% m-% d % H: % M ")
'2017-01-20'

Converts a string to a time object.
Copy codeThe Code is as follows: >>> endtime = datetime. datetime. strptime ('20140901', "% Y % m % d ")
>>> Type (endtime)
<Type 'datetime. datetime'>
>>> Print endtime
2010-07-01 00:00:00

Format the output in seconds from 00:00:00 UTC to the current time
Copy codeThe Code is as follows:
>>> Import time
>>> A = 1302153828
>>> Time. strftime ("% Y-% m-% d % H: % M: % S", time. localtime ())
'2017-04-07 13:23:48'

8. Command Line Parameter Parsing (getopt)

Generally, when writing daily O & M scripts, you must enter different command line options based on different conditions to implement different functions.
In Python, The getopt module is provided to parse the command line parameters. The distance is described below. See the following program:
Copy codeThe Code is 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 :')
Counter t 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 format the output string
Truncates string output. In the following example, only the first three letters of the string are output.
Copy codeThe Code is as follows: >>> str = "abcdefg"
>>> Print "%. 3 s" % str
Abc
Output by fixed width. If space is not used to complete the output, the output width in the following example is 10.
Copy codeThe Code is as follows: >>> str = "abcdefg"
>>> Print "% 10 s" % str
Abcdefg
Truncate the string and output the string according to the fixed width.
Copy codeThe Code is as follows: >>> str = "abcdefg"
>>> Print "% 10.3 s" % str
Abc
Reserved floating point data bits
Copy codeThe Code is as follows: >>> import fpformat
>>> A = 0.0030000000005
>>> B = fpformat. fix (a, 6)
>>> Print B
0.003000
Round the floating point number, 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 hexadecimal conversion

In some cases, different hexadecimal conversions are required. refer to the following example (% x hexadecimal, % d decimal, % o decimal)
Copy codeThe Code is 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 call system commands, the output and return values cannot be obtained in the program.
Copy codeThe Code is as follows: >>> import OS
>>> OS. system ('LS-l/proc/cpuinfo ')
>>> OS. system ("ls-l/proc/cpuinfo ")
-R -- 1 root 0 March 29 16:53/proc/cpuinfo
0

Use OS. popen () to call the system command. The command output can be obtained in the program, but the returned value cannot be obtained.
Copy codeThe Code is as follows: >>> out = OS. popen ("ls-l/proc/cpuinfo ")
>>> Print out. read ()
-R -- 1 root 0 March 29 16:59/proc/cpuinfo

Use commands. getstatusoutput () to call system commands. The program can obtain the return values of command output and execution.
Copy codeThe Code is as follows: >>> import commands
>>> Commands. getstatusoutput ('ls/bin/ls ')
(0, '/bin/ls ')

11. Python captures user Ctrl + C, Ctrl + D events

Sometimes, you need to capture user Keyboard Events in the program, such as ctrl + c exit, so as to better secure exit the program
Copy codeThe Code is as follows: try:
Do_some_func ()
Except t KeyboardInterrupt:
Print "User Press Ctrl + C, Exit"
Failed t EOFError:
Print "User Press Ctrl + D, Exit"

12. Reading and Writing Python files

Reads files to the list at a time, which is fast and applicable when the file is small.
Copy codeThe Code is as follows: track_file = "track_stock.conf"
Fd = open (track_file)
Content_list = fd. readlines ()
Fd. close ()
For line in content_list:
Print line

Row-by-row reading, slow speed, applicable to not enough memory to read the entire file (the file is too large)
Copy codeCode: fd = open (file_path)
Fd. seek (0)
Title = fd. readline ()
Keyword = fd. readline ()
Uuid = fd. readline ()
Fd. close ()

Differences between write and writelines

Fd. write (str): writes str to a file. write () does not add a linefeed after str.
Fd. writelines (content): writes all content to a file. It is written as is without adding anything to the end of each line.


What is python language?

What is Python?

Python is an open-source scripting language that emphasizes development speed and code clarity. It can be used to develop various programs, from simple script tasks to complex and object-oriented applications. Python is also considered as a good language for beginners, because it is free, object-oriented, and highly scalable while implementing strict coding standards.

Python is free of charge

Guido van rosum began developing Python in 1990. Its initial goal was nothing more than a self-entertainment project. As a fan of Monty Python's flying circus program, he gave his own programming language the odd name of the present, which is the Chinese meaning of Python. Python was originally designed as a scripting language to replace the Amoeba distributed operating system ABC, but soon this new programming language quickly developed into a weapon that can solve a considerable number of problems and is now introduced to a variety of platforms.

Guido is also the chairman of the Python Software Foundation. The organization owns the intellectual property and permission of Python as required by the GNU Public License Agreement. Python can be used on a variety of platforms, including Windows, Macintosh and a variety of common UNIX systems. In addition, the corresponding versions of the Pocket PC for PalmOS and Microsoft are also under development.

Superior Python Quality

Although Python is often used to create simple scripts, the programming technology it uses is not simple, such as object-oriented coding, sockets, threads and guis. If you are a new programmer, these features are obviously very helpful to you, because you can quickly get familiar with useful programming syntax and coding practices, and then learn other languages, for example, Java or C ++ introduces more technical concepts. The script can be executed independently. However, you can also use class files and various object types to make full use of the powerful functions of this language.

There are two key differences between Python and other object-oriented languages. First, Python emphasizes space and encoding structure, so that developers' code can be reused. Second, Python code does not need to be compiled before the script is executed, which is why it is used as a script language.

Python is easy to expand

The Python language has a striking advantage in that it can call function libraries for functions that cannot be completed by the language. Python also has some useful tools to help develop complex applications. The most common tool is Tkinker, which enables cross-platform GUI development. Another wxPython tool is an extension of the wxWindows cross-platform C ++ framework. WxPython currently supports Windows and Linux platforms. Python Imaging libraryallows pythonto create a notebook to edit and modify the notebook, such as. gifini.htm and. PNG. To learn about common Python extensions and applications, visit The Vaults of Parnassus.

Python itself can also be embedded into other programming languages. The most common is [url = www.jython.org/mongojythonmongourl.pdf, which is a pythoninterpreter compiled by Java. In this way, you can use the advantages of both languages. You can also create applications that depend on the two language libraries by combining the clear Python syntax in the powerful Java application framework.

Encoding standard

Strict Python syntax is the main reason why Junior programmers ignore this powerful programming language. Unlike most other Web scripting languages, the blank layout of Python does not rely on parentheses or semicolons to indicate the end of a statement. line breaks and Placeholders are used to describe the visual results of the Code. At first glance, this programming method is boring, but it is of great benefit to you. This is the code... the rest of the article>

How to Learn about Python

C ++, Java, and even C # can all be seen as the same type of language: C ++ is flexible, but complicated syntax makes production efficiency low, and Java improves production efficiency, however, flexibility is lost. C # is a good balance between production efficiency and flexibility, but it is still not enough. Otherwise, the father of Boo language will not be angry with Boo. Python is a dynamic type and a strong type language. A dynamic type means that you no longer need to make numerous declarations for the type of each variable, because the compiler will help you make type judgments, it will determine the type of the Variable Based on the Value assignment of the variable. A strong type means that you cannot use a string as an int unless you explicitly convert it. Python itself is compact, because space is ignored in C ++, Java, C #, and "{}" to define code blocks, if you like it, you can write all the code on one line, so you can write it as dizzy as possible. It is not possible, because there is only one Separator in it, namely the colon ":", and the code block is distinguished by indentation. Maybe you will be a bit unaccustomed to this method at the beginning, but later, you will find that this method will benefit you a lot, because you have developed a good code style. Don't think that Python is a very academic language, although many people think it is very suitable as an entry-level language for learning programming. In fact, Python is not only suitable for beginners to learn programming, but also a powerful language. You can use it to do anything other languages can do. Python itself is almost everywhere, and programs written in Python can run in various mainstream operating systems, even Palm. Oh, I almost forgot. Eric Raymond also told us that hackers must master four languages. The first step is Python ., Of course, if you cannot leave. NET in a day, you should start learning Python from IronPython. Compared with C ++, Java, and even C #, is it much faster to write and execute this classic program in Python? Haha ~~~ If I make up my mind to say that Python is highly productive, you will already scold me for being a lie. Okay. Let's try some practical code. But before that, you have to download two very famous class libraries: wxPython and Twisted. Is the download and Installation complete? Let's start our tour of EnjoyPythonwith you in ten minutes. FromwxPython. wximportwxPySimpleApp, wxFrameapp = wxPySimpleApp () frame = wxFrame (None,-1, "HelloWorld ")

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.