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

'注意: 其中 \1 是匹配到的数据,可以通过这样的方式直接引用2、遍历目录方法在某些时候,我们需要遍历某个目录找出特定的文件列表,可以通过os.walk方法来遍历,非常方便1234567891011import osfileList = []rootdir = "/data"for root, subFolders, files in os.walk(rootdir):if '.svn' in subFolders: subFolders.remove('.svn')

# 排除特定目录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)123456789101112>>> 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 uniq)有时候需要将list中重复的元素删除,就要使用如下方法1234567>>> 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、字典排序(dict sort)一般来说,我们都是根据字典的key来进行排序,但是我们如果想根据字典的value值来排序,就使用如下方法12345>>> 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')]从上面的运行结果看到,按照字典的value值进行排序的6、字典,列表,字符串互转以下是生成数据库连接字符串,从字典转换到字符串12345>>> 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'下面的例子 是将字符串转化为字典123456>>> 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、时间对象操作123456789101112131415161718192021222324252627282930313233将时间对象转换成字符串>>> import datetime>>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M")

'2011-01-20 14:05' 时间大小比较>>> 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 时间差值计算,计算8小时前的时间>>> 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' 将字符串转换成时间对象>>> endtime=datetime.datetime.strptime('20100701',"%Y%m%d")>>> type(endtime)

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

'2011-04-07 13:23:48'8、命令行参数解析(getopt)通常在编写一些日运维脚本时,需要根据不同的条件,输入不同的命令行选项来实现不同的功能 在Python中提供了getopt模块很好的实现了命令行参数的解析,下面距离说明。请看如下程序:1234567891011121314151617181920212223242526272829303132333435363738394041424344#!/usr/bin/env python# -*- coding: utf-8 -*-import sys,os,getoptdef 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 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 格式化输出9.1、格式化输出字符串1234567891011121314151617181920212223242526272829截取字符串输出,下面例子将只输出字符串的前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('-1.327433628318584070796460177')>>> Decimal(str(round(c / Decimal(a) * 100, 2)))

Decimal('-1.33')9.2、进制转换有些时候需要作不同进制转换,可以参考下面的例子(%x 十六进制,%d 十进制,%o 八进制)123>>> num = 10>>> print "Hex = %x,Dec = %d,Oct = %o" %(num,num,num)

Hex = a,Dec = 10,Oct = 1210、Python调用系统命令或者脚本12345678910111213141516使用 os.system() 调用系统命令 , 程序中无法获得到输出和返回值>>> import os>>> os.system('ls -l /proc/cpuinfo')>>> 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('ls /bin/ls')

(0, '/bin/ls')11、Python 捕获用户 Ctrl+C ,Ctrl+D 事件有些时候,需要在程序中捕获用户键盘事件,比如ctrl+c退出,这样可以更好的安全退出程序123456try:

do_some_func()except KeyboardInterrupt:

print "User Press Ctrl+C,Exit"except EOFError:

print "User Press Ctrl+D,Exit"12、Python 读写文件1234567891011121314151617181920一次性读入文件到列表,速度较快,适用文件比较小的情况下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的内容全部写到文件中,原样写入,不会在每行后面加上任何东西

python编程基础知识点总结_【转载】Python编程中常用的12种基础知识总结相关推荐

  1. Python 编程中常用的12种基础知识总结

    Python 编程中常用的12 种基础知识总结:正则表达式替换,遍历目录方法,列表按列排序.去重,字典排序,字典.列表.字符串互转,时间对象操作,命令行参数解析(getopt),print 格式化输出 ...

  2. python编程中常用的12种基础知识总结

    python编程中常用的12种基础知识总结:正则表达式替换,遍历目录方法,列表按列排序.去重,字典排序,字典.列表.字符串互转,时间对象操作,命令行参数解析(getopt),print 格式化输出,进 ...

  3. python中 12_python编程中常用的12种基础知识总结

    1.正则表达式替换 目标: 将字符串line中的 overview.gif 替换成其他字符串 >>> line =' >>> mo=re.compile(r'(?& ...

  4. python解放二次开发_[转载]Python二次开发程序详解

    ###################################### ## Fundamentschwingungsstudie ## ## nur geeignet fuer ABAQUS ...

  5. python二级选择题及答案_转载 |python二级选择题与分析(6)

    算法的时间复杂度是指 A 执行算法程序所需要的时间 B 算法程序的长度 C 算法程序中的指令条数 D 算法执行过程中所需要的基本运算次数 正确答案: D 下列关于栈的叙述中正确的是 A 在栈中只能插入 ...

  6. python编程基础知识点_12个关于Python编程基础知识的总结

    学习任何语言的时候,打好基础非常重要.就像学英文,要知道26个字母,还要学会单词.句型.语法等等.那么Python编程也一样,对于刚入门学习的人更应该打好基础.下面课课家收集了常用的12种Python ...

  7. python中常用的九种预处理方法

    本文总结的是我们大家在python中常见的数据预处理方法,以下通过sklearn的preprocessing模块来介绍; 1. 标准化(Standardization or Mean Removal ...

  8. python数据预处理的方法_python中常用的九种数据预处理方法

    python中常用的九种预处理方法分享 本文总结的是我们大家在python中常见的数据预处理方法,以下通过sklearn的preprocessing模块来介绍; 1. 标准化(Standardizat ...

  9. python程序设计从基础到开发课后题答案夏敏捷_[转载] python程序设计应用教程夏敏捷答案第八章_Python程序设计:从基础到开发...

    参考链接: 用Python设计键盘记录器 基础篇 第1章Python语言介绍 1.1Python语言简介 1.2安装与配置Python环境 1.2.1安装Python 1.2.2运行Python 1. ...

最新文章

  1. Oracle 添加RAC数据库集群节点(一)
  2. python精度丢失_JS大坑之19位数的Number型精度丢失问题详解_稚终_前端开发者
  3. java utf8转iso8859-1_Java字符编码处理(UTF-8/ISO-8859-1)之一 –读文本文件乱码问题 | 学步园...
  4. 2020年11月 Oracle WebLogic 高危预警:CVE-2020-14750 无需认证攻击
  5. 传输层学习之五(TCP的SACK,F-RTO)
  6. exception EOleSysError in module HLServer.exe at 0009C451.问题解决
  7. 完全卸载mysql数据库
  8. 二维热传导 matlab,二维热传导方程数值解及MATLAB实现.docx
  9. java字节码查看器_jclasslib 下载
  10. deepstream-test3
  11. 【BP-GA】基于GA的BP神经网络优化算法
  12. 安装Sublime Text 3插件的方法:
  13. 生活记录:压抑暂时解脱
  14. Amazon CloudWatch 介绍/学习
  15. java-之冒泡排序法
  16. android怎么加矩形框,Android shape 矩形框子
  17. 软件测试之实用小工具推荐
  18. 【妇女节特辑】闪耀的工程师女性们
  19. life is hard
  20. 数据库连接池HikariCP

热门文章

  1. 青岛市人才市场2008年11月份交流会安排
  2. Windows下Scala+Spark+IDEA+Hadoop环境搭建
  3. java实现斗地主洗牌发牌功能
  4. 10 款 Linux 环境下的开源替代工具
  5. SQL取日期时间部分
  6. 中国人发明的代码,你知道是什么样的吗?
  7. Java精品项目源码第127期新闻发布网站系统
  8. Docker官网浅学---最原汁原味的Docker循序渐进接触之旅
  9. 宏观经济学第13版多恩布什笔记和答案
  10. 【3D打印机】3D打印小妙招之“缩短等待打印时间” :在打印开始时同时加热喷嘴和热床。