Python基础知识总结

来源:互联网 发布:淘宝网店项目战略目标 编辑:程序博客网 时间:2024/05/15 02:00

1.退出终端:ctrl+D;


2.raw_input()与input()区别:前者输入字符串时,无需加入引号,后者需加入引号。


3.path='rc:\a'

   path2=r'c:\\a'

print path,path2

原始字符串以r 开头,则不会转义\


4.a=[1,2,3,4]获取3,4如下:

a[2:]  、a[2:4]


5.序列:列表 和元组;其中列表可修改,元组不可修改;


6.list函数可将字符串分片处理;

如a=list('1234')   print a    a=['1','2','3','4']

分片赋值:a[3:]=list('5','6')  print a   a','3','5=['1','2','6']

删除:del a[3]  print a   a=['1','2','3','6']

列表的方法:

append:在列表后追加新对象,如a.append('4')

count:计算某个数在列表中出现的个数,如a.count(3)

extend:扩展多个列表,如b=list('09')  a.extend(b)

index:求某个元素首次出现的索引 ;如a.index('2')

pop:移除列表元素的元素,默认为最后一个元素;如a.pop()

remove:移除列表的元素,如a.remove('1')

reverse:反位;如a.reverse() 

sort:排序;如a.sort()


7.元组:

 tuple:以序列为参数创建元组;如tuple(['1','2'])  tuple(list('12'))

单个元组:如12,   ---得到(12)



8.字符串:

所有标准的序列操作(索引、分片、乘法、判断成员资格、求长度、取最小值和最大值)对字符串同样适用,注意字符串都是不可变的。

字符串操作:

find:'hello world'.find('w')

join:'+'.join([1,2,3])  ----得到1+2+3

split:a.split('+')

lower():a.lower()

replace():a.replace('he','ss')

strip():去除字符串头尾的空格(不包含内部);如'   hello  world   '.strip()----得到'hello  world'


9.字典:由键值组成;

创建方式:

1) a={'name':'fww'}

2)a={('name','fww'),('age',20)}    b=dict(a)

3)   a=dict(name='fww',age=20)


10.global:可将变量申明为全局;

  默认参数:通过直接在函数中设置参数的默认值,如 def default(a,b,c=2)

  关键参数:通过参数名称来设置,如def default(a,b=2,c=3)    default(c=1,a=2)


11.捕捉异常:(try....except)

try :10/0 except: print 'error'


12.构造方法:即__init__()


13.类继承:

#申明为新式类:因为super只能在新式类中使用;
__metaclass__=type

class bird:
    def __init__(self):
        self.hungry=True
    def eat(self):
        if self.hungry==True:
            print 'eat'
            self.hungry=False
        else:
            print 'not hungry'

class songbird(bird):
    def __init__(self):
        #两种调用父类的构造方法;bird.__init__(self)、 super(songbird,self).__init__()
        #bird.__init__(self)
        super(songbird,self).__init__()
        self.sound='ahahha'

        self.singer='fww'
        self.song='go on!'

#info为虚拟属性;(singer,song)----等同于info

    def setSong(self,info):
        self.singer,self.song=info

    def getSong(self):
        return self.singer,self.song 

    def sing(self):
        print self.sound

info=property(getSong,setSong)

sb.singer='fxl'
sb.song='hello'

sb.info='fxl','hello'      #等同于上;

print sb.info               #sb.info

print sb.getSong()
sb.setSong(('fsq','father'))
print sb.singer,sb.song


14.迭代器:iter

内建的迭代函数:iter;如it=iter([1,2,3])   it.next()--1;  it.next()--2;

__iter__():是迭代器规则的基础。

如:
class TestIter:
    value=0
    def next(self):
        self.value+=1
        if self.value>10:
            raise StopIteration
        return self.value
        
    def __iter__(self):
        return self
ti=TestIter()
print list(ti)

15.创建生成器:

def flatten(num):
    for st in num:
        for s in st:
            yield s
num=[[1,2],[3,4],[5]]
for n in flatten(num):
    print n

#利用list生成列表;

print list(flatten(num))


16.递归生成器:

def fla(aa):
    try:
        for bb in aa:
            for cc in fla(bb):
                yield cc
    except TypeError:
        yield aa
list(fla([[[1],2],3,4,[5,[6,7]],8]))  #注意括号层次比较多
[1, 2, 3, 4, 5, 6, 7, 8]


17.查找模块的位置:  sys.path   可告诉编译器查找的位置:sys.path.append('c:/python')


18.random方法:

>>> values = range(1,13) + 'dwang xwang'.split()  #定义13个数字与大小王
>>> suits = 'hei hong mei fang '.split()           # 定义牌的四种类型(黑、红、梅、方)
>>> deck = ['%s of %s' %(v ,s ) for v in values for s in suits]  #循环嵌套将其循环组合
>>> from pprint import pprint   #调用pprint 模块
>>> pprint (deck [:18])         #输出18张牌
['1 of hei',
 '1 of hong',
 '1 of mei',
 '1 of fang',
 '2 of hei',
 '2 of hong',
 '2 of mei',
 '2 of fang',
 '3 of hei',
 '3 of hong',
 '3 of mei',
 '3 of fang',
 '4 of hei',
 '4 of hong',
 '4 of mei',
 '4 of fang',
 '5 of hei',
 '5 of hong']


#显然上面的输出太整齐,调用随机函数,随机一点
>>> from random import shuffle
>>> shuffle(deck)
>>> pprint(deck[:18])
['5 of fang',
 '6 of hong',
 '5 of mei',
 'dwang of fang',
 'xwang of fang',
 '10 of hong',
 '7 of mei',
 '12 of hong',
 '6 of hei',
 '12 of hei',
 '7 of hei',
 '8 of hei',
 '4 of fang',
 'dwang of hei',
 '11 of hei',
 '12 of fang',
 '5 of hei',
 '2 of hong']



19.正则表达式re:

re包括如下函数:


如str='fww,,will be ,,successful!'

compile:

search:根据匹配表达式来匹配字符串,若匹配成功,返回True;  如 if re.search('[succ]',str): print 'find it!'

split:根据匹配表达式来分割字符串;如 re.split('[,]+',str)   得到['fww','will be' ,'successful!']   以匹配[,]+

findall:根据匹配表达式从字符串中找到所有匹配项目,以列表形式返回;如re.findall('[a-zA-Z]+',str)   得到['fww','will be','successful']

sub:将字符串中所有pat的匹配项用text代替; pat='{name}'  text='Dear {name}' re.sub(pat,'fww 1989',text)  得到Dear fww 1989


20.组group:在()内  其中re.end(group)   为该组最后个字符的索引+1;


如str='www.baidu.com'

re.match('www\.(.*)\..{3}',str)

print re.group(),re.group(0),re.group(1),re.start(1),re.end(1),re.span(1)  得到www.baidu.com  www.baidu.com  baidu 4  9  (4,9)




















0 0
原创粉丝点击