Python是很多公司都在使用的一种脚本语言,其语法与Perl、C++、JAVA等都大同小异。本文仅对一些比较常用的语法结构进行总结,比如字典、列表、正则匹配、读写文件等。供广大喜爱Python的同学学习交流。
字符串操作
- 去除特殊符号:s.strip() .lstrip() .rstrip(',')
- 拼接字符串:str = str1 + str2
- 连接字符串:lis = ['1','2','3'] str.join(lis)
- 查找字符串:str1
=
'hello world' str2 = 'o' pos = str1.index(str2) - 比较字符串:cmp(str1,str2)
- 字符串长度:len(str)
- 字符串复制:n * str
- 大小写转换:str.upper() str.lower()
- 翻转字符串:str1 = str2[::-1]
- 截取字符串:str[0:3] #截取第一位到第三位的字符
str[-3:-1] #截取倒数第三位与倒数第一位之间的字符
str[-3:]#截取倒数第三位到结尾的字符
- 分割字符串:array = str.split(':') #将以:分割的字符串存入数组array
数组
数组是一种列表结构,可以嵌套
- 定义:arr = [1,2,[1,2,3]]
- 删除元素:del arr[0,2]
- 插入元素:arr.append(4)
- 数组长度:len(arr)
- 遍历数组:
for i in range(len(arr)):
print arr[i]
字典
字典是由键=>值对构成的结构,可以嵌套.
- 创建字典:
直接创建:fruitDic = {"apple":1,"orange":2,"banana":3}
dict函数创建:fruitDic = dict(("apple","orange","banana"),(1,2,3)) 或 fruitDic = dict("apple"=1,"orange"=2,"banana"=3)
- 清空字典:fruitDic.clear()
- 复制字典:这里要注意浅复制和深复制的问题。浅复制是指复制对象,新字典的改变内容会使原字典也改变;对于深复制,新字典的改变不会影响原来的字典。
浅复制方式:newDic = origDic.copy()
深复制方式:from copy import deepcopy
newDic =deepcopy(origDic)
- 判断字典是否包含某键:dict.has_key('apple')
- 字典的键值:dict.keys() dict.values()
- 移除某键值对:dict.pop('apple')
- 字典遍历:
for i in dict:
print dict[i]
for (k,v) in dict.items(): #dict.items()表示返回-字典中(键, 值)对元组的列表
print "%s:%s" %k,v
for k,v in dict.iteritems(): #dict.iteritems()表示返回一个迭代对象
print "%s:%s" %k,v
正则匹配
Python的re模块提供了各种正则表达式的匹配操作,在文本解析、复杂字符串分子以及信息提取时非常有效,在脚本中应加入import re。
1. 正则表达式是否匹配字符串的全部或部分
str = 'I love Python.'
regx = '.*love' #正则表达式,可参见另一篇博客。
if re.search(regx, str):
print "match"
else:
print "not match"
2. 正则表达式是否匹配整个字符串
if re.match(regx, str):
print "match"
else:
print "not match"
3. 获取匹配部分:
使用group()函数,正则表达式中圆括号匹配的模式,分别对应group(1),group(2),...。而group()则对应最大匹配结果。
str = 'I love Python and JAVA.'
regx = 'I love (.*) and (.*)' #正则表达式,可参见另一篇博客。
match = re.search(regx, str)
if match:
print match.group(1)+'\t'+match.group(2) #显示结果为 Python JAVA
else:
print "not match"
4. 将所有匹配的子串存入数组:
array = re.findall(regx, str)
5. 创建正则表达式对象
另外,还可以通过compile函数创建一个正则表达式对象,进行相应的匹配。
reobj = re.compile(regx)
match = reobj.search(str)
if match: #或直接 if reobj.match(str): 或 if reobj.search(str):
print match.group(1)+...
else:
print "not match"
同理,也可以将所有匹配子串存入数组:
reobj = re.compile(regx)
array = reobj.findall(str)
读写文件操作
Python中对文件进行读写操作的函数式open():fobj = open(filename,mode)
mode选项:
- r:读文件;
- w:覆盖方式写入文件;
- w+:追加写文件;
- wb:写二进制文件;
1. 按行读文件:
fobj = open("./filename","r")
for line in fobj:
line = line.strip('\n') #去掉换行符
print line
fobj = close()
2. 写文件
fobj = open("./filename","w+")
fobj.write("hello world\n")
fobj = close()
3. 其他文件操作
- fobj.readline():读出一行信息;
- fobj.readlines():读出所有行(即整个文件);
- fobj.writelines(list):把list中的字符串按行写入文件;
逻辑运算符
与:and
或:or
非:not
Others
退出脚本:sys.exit()