Python的一些用法

  前不久学了点python,昨天刚好要处理一个文件,于是拿来试试。

 

  1)正则表达式的使用。

#正则表达式的模块
import re

#正则表达式
rePattern = '.*[0-9]{4}'

pattern = re.compile(rePattern)

#匹配
if pattern.match(line):
    return True
else:
    return False

 

  2)在函数中使用全局变量。

def func():
    global num

 

  3)python默认print输出换行。如果需要输出时不换行,在最后加上逗号即可。

print 'Hello World!',

 

  4)字符串的切分。

  根据某个字符串切分,使用split(),默认参数为空白字符,包括空格、回车、制表符等

strList = strs.split('_')

  如果需要根据多个字符串进行切分,可以使用正则表达式:

#根据空格和水平制表符切分
strList = re.split("[\t\s]", strs)

 

  5)判断一个字符串是否是数字。

if str.isdigit():
    return True
else:
    return False

 

  6)文件的读写

#读文件
fin = file('1.txt', 'r')

#写文件
fout = file('1_ans.txt', 'w')

while True:
    line = fin.readline()
    
        #文件结尾
    if len(line)==0:
        break

    fout.write(line)

fin.close()
fout.close()   

 

  7)列表的使用

ansList = []

#增加列表里的值
ansList.append('Hello1')
ansList.append('Hello2')

#对列表进行排序
ansList.sort()

#遍历输出
for ans in ansList
    print ans

 

posted @ 2012-10-05 10:21  coltfoal  阅读(2335)  评论(9编辑  收藏  举报