网络编程
位置:首页>> 网络编程>> Python编程>> Python的一些用法分享

Python的一些用法分享

  发布时间:2021-04-19 20:49:22 

标签: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
0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com