search
HomeBackend DevelopmentPython TutorialSummary of 12 basic knowledge commonly used in python programming

  Python编程中常用的12种基础知识总结:正则表达式替换,遍历目录方法,列表按列排序、去重,字典排序,字典、列表、字符串互转,时间对象操作,命令行参数解析(getopt),print 格式化输出,进制转换,Python调用系统命令或者脚本,Python 读写文件。

  1、正则表达式替换

  目标: 将字符串line中的 overview.gif 替换成其他字符串

>>> line = &#39;<IMG ALIGN="middle" SRC=\&#39;#\&#39;" /span> 
>>> mo=re.compile(r&#39;(?<=SRC=)"([\w+\.]+)"&#39;,re.I)  

>>> mo.sub(r&#39;"\1****"&#39;,line)  
&#39;<IMG ALIGN="middle" SRC=\&#39;#\&#39;" /span> 

>>> mo.sub(r&#39;replace_str_\1&#39;,line)  
&#39;<IMG ALIGN="middle" replace_str_overview.gif BORDER="0" ALT="">&#39;< /span> 

>>> mo.sub(r&#39;"testetstset"&#39;,line)  
&#39;<IMG ALIGN="middle" SRC=\&#39;#\&#39;" /span>

  注意: 其中 \1 是匹配到的数据,可以通过这样的方式直接引用

  2、遍历目录方法

  在某些时候,我们需要遍历某个目录找出特定的文件列表,可以通过os.walk方法来遍历,非常方便

import os
fileList = []
rootdir = "/data"
for root, subFolders, files in os.walk(rootdir):
if &#39;.svn&#39; in subFolders: subFolders.remove(&#39;.svn&#39;)  # 排除特定目录
for file in files:
  if file.find(".t2t") != -1:# 查找特定扩展名的文件
      file_dir_path = os.path.join(root,file)
      fileList.append(file_dir_path)  

print fileList

  3、列表按列排序(list sort)

  如果列表的每个元素都是一个元组(tuple),我们要根据元组的某列来排序的化,可参考如下方法

  下面例子我们是根据元组的第2列和第3列数据来排序的,而且是倒序(reverse=True)

>>> a = [(&#39;2011-03-17&#39;, &#39;2.26&#39;, 6429600, &#39;0.0&#39;), (&#39;2011-03-16&#39;, &#39;2.26&#39;, 12036900, &#39;-3.0&#39;),
 (&#39;2011-03-15&#39;, &#39;2.33&#39;, 15615500,&#39;-19.1&#39;)]
>>> print a[0][0]
2011-03-17
>>> b = sorted(a, key=lambda result: result[1],reverse=True)
>>> print b
[(&#39;2011-03-15&#39;, &#39;2.33&#39;, 15615500, &#39;-19.1&#39;), (&#39;2011-03-17&#39;, &#39;2.26&#39;, 6429600, &#39;0.0&#39;),
(&#39;2011-03-16&#39;, &#39;2.26&#39;, 12036900, &#39;-3.0&#39;)]
>>> c = sorted(a, key=lambda result: result[2],reverse=True)
>>> print c
[(&#39;2011-03-15&#39;, &#39;2.33&#39;, 15615500, &#39;-19.1&#39;), (&#39;2011-03-16&#39;, &#39;2.26&#39;, 12036900, &#39;-3.0&#39;),
(&#39;2011-03-17&#39;, &#39;2.26&#39;, 6429600, &#39;0.0&#39;)]

  4、列表去重(list uniq)

  有时候需要将list中重复的元素删除,就要使用如下方法

>>> lst= [(1,&#39;sss&#39;),(2,&#39;fsdf&#39;),(1,&#39;sss&#39;),(3,&#39;fd&#39;)]
>>> set(lst)
set([(2, &#39;fsdf&#39;), (3, &#39;fd&#39;), (1, &#39;sss&#39;)])
>>>
>>> lst = [1, 1, 3, 4, 4, 5, 6, 7, 6]
>>> set(lst)
set([1, 3, 4, 5, 6, 7])

  5、字典排序(dict sort)

  一般来说,我们都是根据字典的key来进行排序,但是我们如果想根据字典的value值来排序,就使用如下方法

>>> from operator import itemgetter
>>> aa = {"a":"1","sss":"2","ffdf":&#39;5&#39;,"ffff2":&#39;3&#39;}
>>> sort_aa = sorted(aa.items(),key=itemgetter(1))
>>> sort_aa
[(&#39;a&#39;, &#39;1&#39;), (&#39;sss&#39;, &#39;2&#39;), (&#39;ffff2&#39;, &#39;3&#39;), (&#39;ffdf&#39;, &#39;5&#39;)]

  从上面的运行结果看到,按照字典的value值进行排序的

  6、字典,列表,字符串互转

  以下是生成数据库连接字符串,从字典转换到字符串

>>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}
>>> ["%s=%s" % (k, v) for k, v in params.items()]
[&#39;server=mpilgrim&#39;, &#39;uid=sa&#39;, &#39;database=master&#39;, &#39;pwd=secret&#39;]
>>> ";".join(["%s=%s" % (k, v) for k, v in params.items()])
&#39;server=mpilgrim;uid=sa;database=master;pwd=secret&#39;

  下面的例子 是将字符串转化为字典

>>> a = &#39;server=mpilgrim;uid=sa;database=master;pwd=secret&#39;
>>> aa = {}
>>> for i in a.split(&#39;;&#39;):aa[i.split(&#39;=&#39;,1)[0]] = i.split(&#39;=&#39;,1)[1]
...
>>> aa
{&#39;pwd&#39;: &#39;secret&#39;, &#39;database&#39;: &#39;master&#39;, &#39;uid&#39;: &#39;sa&#39;, &#39;server&#39;: &#39;mpilgrim&#39;}

  7、时间对象操作

将时间对象转换成字符串
>>> import datetime
>>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
  &#39;2011-01-20 14:05&#39; 

时间大小比较
>>> import time
>>> t1 = time.strptime(&#39;2011-01-20 14:05&#39;,"%Y-%m-%d %H:%M")
>>> t2 = time.strptime(&#39;2011-01-20 16:05&#39;,"%Y-%m-%d %H:%M")
>>> t1 > t2
  False
>>> t1 < t2
  True 

时间差值计算,计算8小时前的时间
>>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
  &#39;2011-01-20 15:02&#39;
>>> (datetime.datetime.now() - datetime.timedelta(hours=8)).strftime("%Y-%m-%d %H:%M")
  &#39;2011-01-20 07:03&#39; 

将字符串转换成时间对象
>>> endtime=datetime.datetime.strptime(&#39;20100701&#39;,"%Y%m%d")
>>> type(endtime)
  <type &#39;datetime.datetime&#39;>
>>> print endtime
  2010-07-01 00:00:00 

将从 1970-01-01 00:00:00 UTC 到现在的秒数,格式化输出   

>>> import time
>>> a = 1302153828
>>> time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(a))
  &#39;2011-04-07 13:23:48&#39;

  8、命令行参数解析(getopt)

  通常在编写一些日运维脚本时,需要根据不同的条件,输入不同的命令行选项来实现不同的功能 在Python中提供了getopt模块很好的实现了命令行参数的解析,下面距离说明。请看如下程序:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys,os,getopt
def usage():
print &#39;&#39;&#39;&#39;&#39;
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"
&#39;&#39;&#39; 

try:
opts, args = getopt.getopt(sys.argv[1:],&#39;he:c:f:d:n:s:&#39;)
except getopt.GetoptError:
usage()
sys.exit()
if len(opts) == 0:
usage()
sys.exit()  

for opt, arg in opts:
if opt in (&#39;-h&#39;, &#39;--help&#39;):
  usage()
  sys.exit()
elif opt == &#39;-d&#39;:
  print "del stock %s" % arg
elif opt == &#39;-f&#39;:
  print "read file %s" % arg
elif opt == &#39;-c&#39;:
  print "user-defined %s " % arg
elif opt == &#39;-e&#39;:
  print "Exchange Name %s" % arg
elif opt == &#39;-s&#39;:
  print "Stock code %s" % arg
elif opt == &#39;-n&#39;:
  print "Stock name %s" % arg  

sys.exit()

  9、print 格式化输出

  9.1、格式化输出字符串

截取字符串输出,下面例子将只输出字符串的前3个字母
>>> str="abcdefg"
>>> print "%.3s" % str
  abc
按固定宽度输出,不足使用空格补全,下面例子输出宽度为10
>>> str="abcdefg"
>>> print "%10s" % str
     abcdefg
截取字符串,按照固定宽度输出
>>> str="abcdefg"
>>> print "%10.3s" % str
         abc
浮点类型数据位数保留
>>> import fpformat
>>> a= 0.0030000000005
>>> b=fpformat.fix(a,6)
>>> print b
  0.003000
对浮点数四舍五入,主要使用到round函数
>>> from decimal import *
>>> a ="2.26"
>>> b ="2.29"
>>> c = Decimal(a) - Decimal(b)
>>> print c
  -0.03
>>> c / Decimal(a) * 100
  Decimal(&#39;-1.327433628318584070796460177&#39;)
>>> Decimal(str(round(c / Decimal(a) * 100, 2)))
  Decimal(&#39;-1.33&#39;)

  9.2、进制转换

  有些时候需要作不同进制转换,可以参考下面的例子(%x 十六进制,%d 十进制,%o 十进制)

>>> num = 10
>>> print "Hex = %x,Dec = %d,Oct = %o" %(num,num,num)
  Hex = a,Dec = 10,Oct = 12

  10、Python调用系统命令或者脚本

使用 os.system() 调用系统命令 , 程序中无法获得到输出和返回值
>>> import os
>>> os.system(&#39;ls -l /proc/cpuinfo&#39;)
>>> os.system("ls -l /proc/cpuinfo")
  -r--r--r-- 1 root root 0  3月 29 16:53 /proc/cpuinfo
  0 

使用 os.popen() 调用系统命令, 程序中可以获得命令输出,但是不能得到执行的返回值
>>> out = os.popen("ls -l /proc/cpuinfo")
>>> print out.read()
  -r--r--r-- 1 root root 0  3月 29 16:59 /proc/cpuinfo  

使用 commands.getstatusoutput() 调用系统命令, 程序中可以获得命令输出和执行的返回值
>>> import commands
>>> commands.getstatusoutput(&#39;ls /bin/ls&#39;)
  (0, &#39;/bin/ls&#39;)

  11、Python 捕获用户 Ctrl+C ,Ctrl+D 事件

  有些时候,需要在程序中捕获用户键盘事件,比如ctrl+c退出,这样可以更好的安全退出程序

try:
    do_some_func()
except KeyboardInterrupt:
    print "User Press Ctrl+C,Exit"
except EOFError:
    print "User Press Ctrl+D,Exit"

  12、Python 读写文件

一次性读入文件到列表,速度较快,适用文件比较小的情况下
track_file = "track_stock.conf"
fd = open(track_file)
content_list = fd.readlines()
fd.close()
for line in content_list:
    print line  

逐行读入,速度较慢,适用没有足够内存读取整个文件(文件太大)
fd = open(file_path)
fd.seek(0)
title = fd.readline()
keyword = fd.readline()
uuid = fd.readline()
fd.close()  

写文件 write 与 writelines 的区别   

Fd.write(str) : 把str写到文件中,write()并不会在str后加上一个换行符
Fd.writelines(content) : 把content的内容全部写到文件中,原样写入,不会在每行后面加上任何东西

               

The above is the detailed content of Summary of 12 basic knowledge commonly used in python programming. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What data types can be stored in a Python array?What data types can be stored in a Python array?Apr 27, 2025 am 12:11 AM

Pythonlistscanstoreanydatatype,arraymodulearraysstoreonetype,andNumPyarraysarefornumericalcomputations.1)Listsareversatilebutlessmemory-efficient.2)Arraymodulearraysarememory-efficientforhomogeneousdata.3)NumPyarraysareoptimizedforperformanceinscient

What happens if you try to store a value of the wrong data type in a Python array?What happens if you try to store a value of the wrong data type in a Python array?Apr 27, 2025 am 12:10 AM

WhenyouattempttostoreavalueofthewrongdatatypeinaPythonarray,you'llencounteraTypeError.Thisisduetothearraymodule'sstricttypeenforcement,whichrequiresallelementstobeofthesametypeasspecifiedbythetypecode.Forperformancereasons,arraysaremoreefficientthanl

Which is part of the Python standard library: lists or arrays?Which is part of the Python standard library: lists or arrays?Apr 27, 2025 am 12:03 AM

Pythonlistsarepartofthestandardlibrary,whilearraysarenot.Listsarebuilt-in,versatile,andusedforstoringcollections,whereasarraysareprovidedbythearraymoduleandlesscommonlyusedduetolimitedfunctionality.

What should you check if the script executes with the wrong Python version?What should you check if the script executes with the wrong Python version?Apr 27, 2025 am 12:01 AM

ThescriptisrunningwiththewrongPythonversionduetoincorrectdefaultinterpretersettings.Tofixthis:1)CheckthedefaultPythonversionusingpython--versionorpython3--version.2)Usevirtualenvironmentsbycreatingonewithpython3.9-mvenvmyenv,activatingit,andverifying

What are some common operations that can be performed on Python arrays?What are some common operations that can be performed on Python arrays?Apr 26, 2025 am 12:22 AM

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

In what types of applications are NumPy arrays commonly used?In what types of applications are NumPy arrays commonly used?Apr 26, 2025 am 12:13 AM

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

When would you choose to use an array over a list in Python?When would you choose to use an array over a list in Python?Apr 26, 2025 am 12:12 AM

Useanarray.arrayoveralistinPythonwhendealingwithhomogeneousdata,performance-criticalcode,orinterfacingwithCcode.1)HomogeneousData:Arrayssavememorywithtypedelements.2)Performance-CriticalCode:Arraysofferbetterperformancefornumericaloperations.3)Interf

Are all list operations supported by arrays, and vice versa? Why or why not?Are all list operations supported by arrays, and vice versa? Why or why not?Apr 26, 2025 am 12:05 AM

No,notalllistoperationsaresupportedbyarrays,andviceversa.1)Arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,whichimpactsperformance.2)Listsdonotguaranteeconstanttimecomplexityfordirectaccesslikearraysdo.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft