python 基础知识

1.list列表

1.1定义:

list=[]

1.2遍历

for item in list:
      print item

1.3操作

增:

list.append('hello')

删:

list.remove('hello')

改:

list[0]='hello'

查:

if 'hello' in list:
    print 'Y'
else:
    print 'N'

插入:

list.insert(0,'hello')
1.4判断

判断list 是否为空

if list:
    print 'has items'
else:
    print 'empty'

2.dict字典

2.1定义:

dict={}

2.2遍历

for key in dict:
      print 'key:'+key+',value:'+dict[key]

2.3操作

增:

dict['hello']='world'

删:

del dict['hello']

改:

dict['hello']='world'

查:

if dict.has_key('hello'):
    print 'Y'
else:
    print 'N'

清空:

dict.clear()
2.4判断

判断dict 是否为空

if dict:
    print 'has items'
else:
    print 'empty'

3.set()无重复列表

3.1定义:

s=set()

3.2遍历

for item in list:
      print item

3.3操作

增:

s.add('hello')

删:

s.remove('hello')

查:

if 'hello' in s:
    print 'Y'
else:
    print 'N'
3.4判断

判断set 是否为空

if s:
    print 'has items'
else:
    print 'empty'

忽略输出警告

import warnings
warnings.filterwarnings("ignore")

range

>>> n=range(4)
>>> n
[0, 1, 2, 3]
>>> m = range(2,7)
>>> m
[2, 3, 4, 5, 6]

字符串匹配

>>> pattern = 'hello'
>>> str = 'kk*hello*kk'
>>> if pattern in str:
...     print 'find:'+pattern
... else:
...     print 'not find'
...
find:hello

中文匹配

#!/usr/bin/python
#-*-coding:utf-8 -*-

import os,sys

reload(sys)
sys.setdefaultencoding('utf-8')
pattern = '中文'.encode('utf-8')
longstr = 'kk*中文*kk'.encode('utf-8')
if pattern in longstr:
     print 'find:'+pattern
 else:
     print 'not find'

$find:中文

中文处理

#!/usr/bin/python
#-*-coding:utf-8 -*-

import os,sys

reload(sys)
sys.setdefaultencoding('utf-8')

print '中文'.encode('utf-8')

总结

1.False,0,'',[],{},()都可以视为假
2.len(*)方法可以测量列表、字典、set的长度

你可能感兴趣的:(python 基础知识)