一 概述
解释性语言。OO
有命令行模式,可以直接输入语句,得到结果。
二 字符串操作
1. 可以拼接
>>> 'abc'+'fff'
'abcfff'
2. 可以复制
>>> 'abc'*3
'abcabcabc'
3. 可以通过函数操作
>>> len('abc')
3
4. string类型变量可以有成员函数操作。具体参考 help('string')
>>> s='abc'
>>> s.rfind('a')
0
5. 可以使用[]从字符串取字符
>>> a='abcde'
>>> a[3]
'd'
>>>
6. 字符串切片
>>> a[1:3]
'bcd'
>>> a[2:]
'cde'
7. 搜索
find(words, letter)
words.find('a',1,100) # 查找words从1 到100之间的char是否有'a',没有则返回-1,有则返回位置
8. in 操作符
>>> 'a' in 'abcd'
True
三 函数定义
def fun1():
def fun2(param):
return 100
标准函数:
1. raw_input() #标准输入
2. print #标准输出
3. isinstance(param,int) #检查变量类型
四 循环
for i in range(4):
for i in range(70-len):
for i in dict:
while xxxxx :
支持break 语句
五 操作符号
1. 求模 /
2. 求余 %
3. 逻辑操作 and or not
六 判断
if :
elif :
else :
七 列表和字典
1. 定义
list1 =[1,2,3,4,5]
strlist=['a','ab','d']
dictionary=dict() #dict() 是构造字典的函数, python 使用hash table查找字典
2. 遍历
for i in list1:
for i in dictionary:
3. 列表切片
list1[1:4]
4. 列表内函数
a. t.append('a') #t尾部加入元素
b. t = t+t1 t.append(t1) # t尾部加入表t1
c. t.sort() #对表t排序 无返回值
d. t.pop(n) #删除表的第n个元素
e. del t[1:5] #删除表的第1 到 5 元素
f. t.remove('b') #删除表中值为'b'的元素
5. 字典的函数
len(dictionary)
6. 元组定义
定义之后不可改变,可以使用[ ]取元组数据,类似列表。
t = 'a',
t = 'a','b'
t = tuple()
元组的分散
* 可以使元组分散。
1)函数参数,可以使函数接受不定长参数
def fun1(*args):
print args
2) 当函数只接受一组参数时,将元组打散使其符合函数要求。
a=(7,3)
divmod(*a)
3)元组和列表的组合及排序
sort(...)
L.sort(cmp=None, key=None, reverse=False)
八 对象引用和值
1. 如果a是一个对象,b=a, 则b是a的引用
>>> a =[1,2,3]
>>> b=a
>>> b is a
True
>>> b.append(10)
>>> b is a
True
>>> a
[1, 2, 3, 10]
>>>
2. 定义的两个值相同的字符串,是引用,当一个值变动的时候,则变成两个对象。如果改回原值,则又成为引用。
>>> c='abc'
>>> d='abc'
>>> c is d
True
>>> d=d+'a'
>>> print d
abca
>>> print c
abc
>>> d is c
False
>>>
九 异常处理
1. raise 发出异常
>>> raise ValueError, 'this is an exmaple'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: this is an exmaple
2. 捕获异常
try:
works.....
except:
print ....
十 文件和数据库
1. 文件
f=open('file.txt','w') # r:read, w:write, c:create
f.write('write a file\n')
f.close()
for line in f: # 按行读取文件
......
2. 目录
import os
os.getcwd()
os.path.abspath('file.txt')
os.path.exists(
'file.txt')
os.path.isdir('file')
os.listdir('dir')
os.path.isfile('file.txt')
3. 数据库
import anydbm
数据库操作与文件相同,key与value都必须是字符串。pickle模块可以帮助用户将各种数据转换成db可以保存的格式。
import pickle
t = [1,2,3]
s=pickle.dumps(t)
pickle.loads(s)
4. 管道
cmd='ls -l'
f=os.popen(cmd)
f.read()
f.close()
十一 类和对象
定义类和方法
class Time(object): #object is internal class
attributes: hour, min, sec #类属性
def func(): #类方法
xxxxxxxxxxxxx
def __init__(self, hour, min, sec): #特殊方法,初始化类实例使用,形参可选
def __str__(self): #特殊方法,返回累的字符串表达式
def __add__(self, other): #重载运算符方法 +
十二 正则表达式
import re
3433

被折叠的 条评论
为什么被折叠?



