队列:先进先出
list = ["apple", "banana", "grape"]
list.append("orange")
print list
print "Pop:",list.pop(0)
堆栈:先进后出
print "Pop:",list.pop()
2. 切片
#! /usr/bin/env python
#coding=utf-8
tuple = ("apple", "banana", "grape", "orange")
print tuple[:3] #取开头到第三个元素
print tuple[3:] #取第四个元素到最后一个元素
print tuple[0, -1] #整个数组删除最后一个元素
3. 合并
zip函数接受任意多个序列作为参数,将所有序列按相同的索引组合成一个元素是各个序列合并成的tuple的新序列,新的序列的长度以参数中最短的序列为准。另外(*)操作符与zip函数配合可以实现与zip相反的功能,即将合并的序列拆成多个tuple。
①tuple的新序列
>>>>x=[1,2,3],y=['a','b','c']
>>>zip(x,y)
[(1,'a'),(2,'b'),(3,'c')]
②新的序列的长度以参数中最短的序列为准.
>>>>x=[1,2],y=['a','b','c']
[(1,'a'),(2,'b')]
③(*)操作符与zip函数配合可以实现与zip相反的功能,即将合并的序列拆成多个tuple。
>>>>zip(*zip(x,y))
[(1,2,3),('a','b','c')]
4. 定义常量
在Python中没有提供定义常量的保留字,需要自己定义一个常量类来实现常量的功能!在此提供《Python Cookbook》一书中定义的常量模块const,代码如下:
说明:此类是定义了一个方法__setattr__()和一个异常类型ConstError,主要是判断定义的常量是否在字典中,在则抛出异常,否则,给新创建的常量赋值
class _const:
class ConstError(TypeError):pass
def __setattr__(self,name,value):
if self.__dict__.has_key(name):
raise self.ConstError,"Can't rebind const (%s)"% name
self.__dict__[name]=value
import sys
sys.modules[__name__]=_const()
5.range
<a href="http://hi.baidu.com/life_to_you/item/b31c8db8ba467fe84ec7fd04">http://hi.baidu.com/life_to_you/item/b31c8db8ba467fe84ec7fd04</a>
print range(1, 5)
输出1,2,3,4
print range(1,5,1)
输出1234
print range(1,5,2)
输出1,3
print range(0,5,2)
输出0,2,4
6.正则表达式
import re
s = "HELLO WOLRD"
print re.findall(r"^hello", s, re.IGNORECASE)
7. 读取文件
#读写模式:r只读,r+读写,w新建(会覆盖原有文件),a追加,b二进制文件.常用模式
rU 或 Ua 以读方式打开, 同时提供通用换行符支持 (PEP 278)
w 以写方式打开,
a 以追加模式打开 (从 EOF 开始, 必要时创建新文件)
r+ 以读写模式打开
w+ 以读写模式打开 (参见 w )
a+ 以读写模式打开 (参见 a )
rb 以二进制读模式打开
wb 以二进制写模式打开 (参见 w )
ab 以二进制追加模式打开 (参见 a )
rb+ 以二进制读写模式打开 (参见 r+ )
wb+ 以二进制读写模式打开 (参见 w+ )
ab+ 以二进制读写模式打开 (参见 a+ )
f = file("hello.txt", "w+")
li = ["Sexy boy\n", "test\n"]
f.writelines(li)
f.close()
f = file("hello.txt", "a+")
new_context = "goodbye"
f.write(new_context)
f.close
文件删除
import os
file("hello.txt", "w")
if os.path.exists("hello.txt"):
os.remove("hello.txt")
os.path.split(path)
将path分割成目录和文件名二元组返回。
>>> os.path.split('c:\\csv\\test.csv')
('c:\\csv', 'test.csv')
>>> os.path.split('c:\\csv\\')
('c:\\csv', '')
os.path.join(path1[, path2[, ...]])
将多个路径组合后返回,第一个绝对路径之前的参数将被忽略。
>>> os.path.join('c:\\', 'csv', 'test.csv')
'c:\\csv\\test.csv'
>>> os.path.join('windows\temp', 'c:\\', 'csv', 'test.csv')
>>> os.path.join('/home/aa','/home/aa/bb','/home/aa/bb/c')
'/home/aa/bb/c'
8.批量修改文件名
import shutil
files = os.listdir(".")
for filename in files:
pos = filename.find(".")
if filename[pos + 1:] == "html":
newname = filename[:pos + 1] + "htm"
os.rename(filename,newname)
li = os.path.splitext(filename)
if li[1] == ".html":
newname = li[0] + ".htm"
os.rename(filename, newname)
9. 在文件中查找内容
#!/usr/bin/python
# -*- coding: UTF-8 -*-
f1 = file("hello.txt", "r")
count = 0
for s in f1.readlines():
li = re.findall("test", s)
if len(li) > 0:
count = count + li.count("test")
print "find " + str(count) + " test"
10.读取配置文件
import ConfigParser
config = ConfigParser.ConfigParser()
config.read(“ODBC.ini”)
#获取配置块
config.sections()
#获取配置项
config.options()
#获取配置内容
config.iteams()
#根据配置快和配置项返回内容
config.get()
写入配置文件
添加配置快
config.add_section()
设置配置项和配置内容
config.set
修改配置项和配置内容
config.set()
删除配置文件
删除配置项
remove_options
删除配置块
remove_section
11.目录的添加删除操作
os.mkdir("hello")
os.rmdir("hello")
os.makedirs("hello/world")
os.removedirs("hello/world")
12. 目录的遍历
def VisitDir(path):
li = os.listdir(path)
for p in li:
pathname = os.path.join(path, p)
if not os.path.isfile(pathname):
VisitDir(pathname)
else:
print pathname
if __name__ == "__main__":
path = r"C:\windows"
VisitDir(path)
13. 文件流(输出流 输出到文件)
import sys
sys.stdout = open(r"./hello.txt", "a")
print "\ngoodbye\n"
sys.stdout.close()
输入流读取文件输入到屏幕设备上
sys.stdin = open(r"./hello.txt", "r")
for line in sys.stdin.readlines():
print line
14. 类
定义私有变量用__定义
class Fruit:
def __init__(self):
self.__color = "red" #私有属性定义__
15. 私有变量访问方式
print _Fruit__color
16.抽象类使用
def abstract():
raise NotImplementedError("abstract")
class Fruit:
def __init__(self):
if self.__class__ is Fruit:
abstract()
print "Fruit"
class Apple(Fruit):
Fruit.__init__(self)
print "Apple"
if __name__ == "__main__":
apple = Apple();
17.多态性
def __init__(self, color = None):
self.color = color
def __init__(self, color = "red"):
Fruit.__init__(self,color)
class Banana(Fruit):
def __init__(self, color = "yellow"):
class FruitShop:
def sellFruit(self, fruit):
if isinstance(fruit, Apple):
print "sell apple"
shop = FruitShop()
apple = Apple("red")
banana = Banana("yellow")
shop.sellFruit(apple)
shop.sellFruit(banana)
18. python解析HTML
import BeautifulSoup
import urllib2
soup = BeautifulSoup.BeautifulSoup(page)
print soup
输出
> "C:\Python27\pythonw.exe" -u "C:\Users\Administrator\Desktop\python\pachong\pa.py"
<!doctype html><html><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8" /><title>\xe7\x99\xbe\xe5\xba\xa6\xe4\xb8\x80\xe4\xb8\x8b\xef\xbc\x8c\xe4\xbd\xa0\xe5\xb0\xb1\xe7\x9f\xa5\xe9\x81\x93 </title><style>html,body{height:100%;}html{overflow-y:auto}#wrapper{position:relative;_position:;min-height:100%}#content{padding-bottom:100px;text-align:center;}#ftCon{height:100px;position:absolute;bottom:44px;text-align:center;width:100%;margin:0
auto;z-index:0;overflow:hidden;}#ftConw{width:720px;margin:0 auto;}body{font:12px arial;text-align:;background:#fff}body,p,form,ul,li{margin:0;padding:0;list-style:none}body,form,#fm{position:relative}td{text-align:left}img{border:0}a{color:#00c}a:active{color:#f60}#u{color:#999;padding:4px
no-repeat -304px 0;border:1px solid #b6b6b6;border-color:#9a9a9a #cdcdcd #cdcdcd #9a9a9a;vertical-align:top}.s_ipt{width:405px;height:22px;font:16px/22px arial;margin:5px 0 0 7px;background:#fff;outline:none;-webkit-appearance:none}.s_btn{width:95px;height:32px;padding-top:2px\9;font-size:14px;background:#ddd
no-repeat -202px 0;*position:relative;z-index:0;vertical-align:top}#lg img{vertical-align:top;margin-bottom:3px}#lk{margin:33px 0}#lk span{font:14px "\xe5\xae\x8b\xe4\xbd\x93"}#lm{height:60px}#lh{margin:16px 0 5px;word-spacing:3px}.tools{position:absolute;top:-4px;*top:10px;right:7px;}#mHolder{width:62px;position:relative;z-index:296;display:none}#mCon{height:18px;line-height:18px;position:absolute;cursor:pointer;padding:0
a{width:100%;height:100%;display:block;line-height:22px;text-indent:6px;text-decoration:none;filter:none\9}#mMenu,#user ul{box-shadow:1px 1px 2px #ccc;-moz-box-shadow:1px 1px 2px #ccc;-webkit-box-shadow:1px 1px 2px #ccc;filter: progid:DXImageTransform.Microsoft.Shadow(Strength=2,
Direction=135, Color="#cccccc")\9;}#mMenu{width:56px;border:1px solid #9b9b9b;list-style:none;position:absolute;right:27px;top:28px;display:none;background:#fff}#mMenu a:hover{background:#ebebeb}#mMenu .ln{height:1px;background:#ebebeb;overflow:hidden;font-size:1px;line-height:1px;margin-top:-1px}#cp,#cp
a{color:#666666;}#seth{display:none;behavior:url(#default#homepage)}#setf{display:none;}#sekj{margin-left:14px;}</style>
<script type="text/javascript">function h(obj){obj.style.behavior='url(#default#homepage)';var a = obj.setHomePage('http://www.baidu.com/');}</script></head>
<body><div id="wrapper"><div id="content">
<div id="ie6tipcon"></div>
target="_blank" name="tj_reg" class="reg">\xe6\xb3\xa8\xe5\x86\x8c</a></div>
id="fm"><form name="f" action="/s"><span class="s_ipt_wr"><input type="text" name="wd" id="kw" maxlength="100" class="s_ipt" /></span><input type="hidden" name="rsv_bp" value="0" /><input type="hidden" name="rsv_spt" value="3" /><span class="s_btn_wr"><input
type="submit" value="\xe7\x99\xbe\xe5\xba\xa6\xe4\xb8\x80\xe4\xb8\x8b" id="su" class="s_btn" onmousedown="this.className='s_btn s_btn_h'" onmouseout="this.className='s_btn'" /></span></form><span class="tools"><span id="mHolder"><div id="mCon"><span>\xe8\xbe\x93\xe5\x85\xa5\xe6\xb3\x95</span></div></span></span><ul
id="mMenu"><li><a href="#" name="ime_hw">\xe6\x89\x8b\xe5\x86\x99</a></li><li><a href="#" name="ime_py">\xe6\x8b\xbc\xe9\x9f\xb3</a></li><li class="ln"></li><li><a href="#" name="ime_cl">\xe5\x85\xb3\xe9\x97\xad</a></li></ul></div>
id="lm"></p>
</div></body>
</html>
<!--640015f8e5e79ae7-->