Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the common methods in Python programming

2025-03-03 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "what are the commonly used methods in Python programming". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1. Regular expression replacement

Goal: replace the overview.gif in the string line with another string

> line ='

> mo=re.compile (r'(? > > mo.sub)

'To

'To

< /span>

> mo.sub (r'"testetstset"', line)

'To

Note: where\ 1 is the matched data, which can be referenced directly in this way

2. Traversing directory method

At some point, we need to traverse a directory to find a specific list of files, which 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. Sort the list by column (list sort)

If each element of the list is a tuple, we want to sort according to a column of the tuple, you can refer to the following method

For the following example, we sort according to the second and third columns of the tuple, and it is 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 minutes,' 2.33 minutes, 15615500 minutes words 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 deduplication (list uniq)

Sometimes if you need to delete duplicate elements in the list, use the following method

> lst= [(1) recorder sss'), (2) recorder fsdf'), (1) recorder ()), (3)

> 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 sorting (dict sort)

Generally speaking, we sort according to the key of the dictionary, 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": '5miles, "ffff2":' 3'}

> sort_aa = sorted (aa.items (), key=itemgetter (1))

> sort_aa

[('ffff2',' 1'), ('sss',' 2'), ('ffff2',' 3'), ('ffdf',' 5')]

As you can see from the running results above, the value of the dictionary is sorted by

6. Dictionary, list, string conversion

The following is the generation of a database connection string, converted from a dictionary to a string

> params = {"server": "mpilgrim", "database": "master", "uid": "sa", "pwd": "secret"}

> ["% slots% s"% (k, v) for k, v in params.items ()]

['server=mpilgrim',' uid=sa', 'database=master',' pwd=secret']

> ";" .join (["% slots% s"% (k, v) for k, v in params.items ()])

'server=mpilgrim;uid=sa;database=master;pwd=secret'

The following example is to convert 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

Convert a time object to a string

> import datetime

> datetime.datetime.now () .strftime ("% Y-%m-%d% Hava% M")

'2011-01-20 1415 05'

Time size comparison

> import time

> T1 = time.strptime ('2011-01-20 14 05mm, "% Y-%m-%d% HRV% M")

> T2 = time.strptime ('2011-01-20 1614 05mm, "% Y-%m-%d% HRV% M")

> > T1 > T2

False

> T1

< t2   True   时间差值计算,计算8小时前的时间   >

> > datetime.datetime.now () .strftime ("% Y-%m-%d% HGV% M")

'2011-01-20 1514 02'

> (datetime.datetime.now ()-datetime.timedelta (hours=8)). Strftime ("% Y-%m-%d% HRV% M")

'2011-01-20 07VR 03'

Convert a string to a time object

> endtime=datetime.datetime.strptime ('20100701 percent,'% Y%m%d')

> type (endtime)

> print endtime

2010-07-01 00:00:00

The number of seconds from the 00:00:00 UTC of 1970-01-01 to now, formatting the output

> import time

> a = 1302153828

> time.strftime ("Y-%m-%d H:%M:%S", time.localtime (a))

'2011-04-07 13 23 14 48'

8. Command line parameter parsing (getopt)

Usually, when writing some daily operation and maintenance scripts, you need to enter different command line options to achieve different functions according to different conditions. The getopt module provides a good way to parse the command line parameters in Python, which is described below. Please see the following procedure:

#! / 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 -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 ('- hype,'--help'):

Usage ()

Sys.exit ()

Elif opt ='- dumped:

Print's "del stock" arg

Elif opt ='- fallow:

Print's "read file" arg

Elif opt ='- cations:

Print's "user-defined" arg

Elif opt ='- eBay:

Print's "Exchange Name" arg

Elif opt ='- slots:

Print's "Stock code" arg

Elif opt ='- nasty:

Print's "Stock name" arg

Sys.exit ()

9. Print formatted output

9.1. Format the output string

To intercept the string output, the following example outputs only the first three letters of the string > str= "abcdefg" > print "% .3s"% str abc with a fixed width, and does not use space completion. The following example output width is 10 > > str= "abcdefg" > print "s"% str abcdefg intercepts the string. Output according to fixed width > str= "abcdefg" > print ".3s"% str abc floating point data bit retention > import fpformat > a = 0.0030000000005 > b=fpformat.fix (amem6) > print b 0.003000 is rounded to floating point Mainly use 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.3274336283185840707964177') > Decimal (str (round (c / Decimal (a) * 100,2)) Decimal ('- 1.33')

9.2. Binary conversion

Sometimes you need to make different binary conversions, you can refer to the following example (% x hexadecimal,% d decimal,% o octal)

> num = 10

> print "Hex =% xmai Dec =% djime Oct =% o"% (num,num,num)

Hex = a ~ Dec = 10 ~ Oct = 12

10. Python calls system commands or scripts

Using os.system () to call the system command, the output and return values cannot be obtained in the program

> import os

> os.system ('ls-l / proc/cpuinfo')

> > os.system ("ls-l / proc/cpuinfo")

-root root-1 root root 0 March 29 16:53 / proc/cpuinfo

0

Using os.popen () to call the system command, the command output can be obtained in the program, but the return value of execution cannot be obtained.

> out = os.popen ("ls-l / proc/cpuinfo")

> > print out.read ()

-root root-1 root root 0 March 29 16:59 / proc/cpuinfo

Using commands.getstatusoutput () to call system commands, the return values of command output and execution can be obtained in the program.

> import commands

> commands.getstatusoutput ('ls / bin/ls')

(0,'/ bin/ls')

This is the end of the content of "what are the commonly used methods in Python programming". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report