python小练习

# 字符串的反转
def reverse(s):
rt = ''
for i in range(len(s) - 1, -1, -1):
rt += s[i]
return rt
print(reverse('iop09'))

def reverse2(s):
li = list(s)
li.reverse()
rt = "".join(li)
return rt
print(reverse2('ffjjmslkdj9'))

def reverse3(s):
return s[::-1]
print(reverse3('jhbk239'))


def reverse4(s):
return "".join(reversed(s))
print(reverse4('fmko12222200'))

from functools import reduce
def reverse5(s):
return reduce(lambda x, y: y + x, s)
print(reverse5('fmko12222200'))




C:\Users\MOJIE\AppData\Local\Programs\Python\Python36\python.exe C:/Users/MOJIE/PycharmProjects/test/tee.py
90poi
9jdklsmjjff
932kbhj
00222221okmf
00222221okmf

Process finished with exit code 0




清理日志文件
#测试机器的磁盘太小,经常报警,要写一个清理日志的脚本,每次运行就把三天之前的日志删除,日志名的格式是xxx.20170623.log
import os,sys,datetime

PATH = os.getcwd() + '\logs1' #获取日志文件路径 “当前路径+\logs”
now = datetime.datetime.now() #当前时间
delta = datetime.timedelta(days=3) #用来计算3天前的时间
n_days = (now - delta ).strftime('%Y-%m-%d') #获取三天前的日期

for filename in os.listdir(PATH): #循环每个日志文件
log_date = filename.split('.') #以分隔符“.”分割日志文件来截取日期字段2017-11-22
if log_date[1] < n_days:
os.remove(PATH+'\\'+filename) #删除文件(文件路径需要再拼接一下)

#写一个程序,计算min 到max的累加和 如1-100的累加:1+2+3+4+....+100
def AA(min,max):
a = 1
res_sum = 0
for i in range(min,max):
res_sum = a+res_sum
a +=1
return res_sum

print(AA(0,1000))


#计(文件内容)总共写了多少行代码,包括空行和注释,要把代码的行数、空行数、注释行数都统计出来
import string
z = []
S = []
all_str = string.ascii_uppercase + string.ascii_lowercase
print(all_str)
with open('bb.py') as fw:
CONTEXT = fw.readlines()
for i in CONTEXT:
if i.startswith('#'):
z.append(i)

for n in all_str:
if i.startswith(n):
S.append(i)
sumH = len(CONTEXT)
zhusi = len(z)
daima = len(S)
konghang = sumH-zhusi-daima
print('总行数:%s;代码行数:%s;注释行:%s;空行:%s'%(sumH,daima,zhusi,konghang))
# print('总行数:%s;代码行数:%s;注释行:%s;空行:%s'%(len(CONTEXT),len(S),len(z),(sumH-zhusi-daima))) 或者可以用这种方式直接打印出


# 有一个文件,里面有一些敏感词汇,如下,如果输入这些词,就用**代替,然后输出,例如输入今天没吃饭,碰到一个傻逼,原来那个sb是小明。输出今天没吃饭,碰到一个**,原来那个**是小明
def gl():
string = input('please enter string:')
with open('mg',encoding='utf-8') as fw:
context = fw.readlines()
for i in context:
i = i[:-1]
if i in string:
string=string.replace(i,'##')
print(string)
gl()

C:\Users\xiu\AppData\Local\Programs\Python\Python36-32\python.exe C:/Users/xiu/guest/guest/aa.py
please enter string::小明是傻逼,小乐是sb,小红是煞笔,小月是煞比
:小明是##,小乐是##,小红是##,小月是##

Process finished with exit code 0

 

# 通过不引入第三方变量的方式,交换两个变量的值
a = 1
b = 2

a = a+b #a = 1+2 = 3
b = a - b #b = 3-2 = 1
a = a - b #a = 3-1 =2
print(b)
print(a)


对比两个字典中不一样的key和valve值
ok_req={
"version": "9.0.0","is_test": True,"store": "","urs": "","aa":"fff",
"device": {"os": "android","imei": "99001062198893","device_id": "CQliMWEyYTEzNTYyYzk5MzJmCTJlNmY3Zjkx","mac": "02:00:00:00:00:00","galaxy_tag": "CQliMWEyYTEzNTYyYzk5MzJmCTJlNmY3Zjkx",
"udid": "a34b1f67dd5797df93fdd8b072f1fb8110fd0db6","network_status": "wifi"},
"adunit": {"category": "VIDEO","location": "1","app": "7A16FBB6","blacklist": ""},
"ext_param":{"is_start" : 0,"vId":"VW0BRMTEV"}
}

not_ok={"version": "9.0.0","is_test": True,"urs": "","store": "",
"device": {"os": "android","imei": "99001062298893","device_id": "CQliMWEyYTEzNTYyYzk5MzJmCTJlNmY3Zjkx","mac": "02:00:00:00:00:00",
"galaxy_tag": "CQliMWEyYTEzNTYyYzk5MzJmCTJlNmY3Zjkx",
"udid": "a34b1f67dd5797da93fdd8b072f1fb8110fd0db6",
"network_status": "wifi" },
"adunit": {"category": "VIDEO","location": "1","app": "7A16FBB6","blacklist": ""},
"ext_param": {"is_start": 0,"vid": "VW0BRMTEV"}
}



okkey = []
notkey = []
okvalue = []
notvalue = []

for i in ok_req.keys():
if i not in not_ok.keys():
okkey.append(i)

for i in not_ok.keys():
if i not in ok_req.keys():
notkey.append(i)

for i in ok_req.values():
if i not in not_ok.values():
okvalue.append(i)

for i in not_ok.values():
if i not in ok_req.values():
notvalue.append(i)

print('ok_req 独有的key:%s'%okkey)
print('not_ok 独有的key:%s'%notkey)
print('ok_req 独有的value:%s'%okvalue)
print('not_ok 独有的values:%s'%notvalue)



有一个存着学生成绩的文件,里面存的是json串,json串读起来特别不直观,需要你写代码把它都写到excel中,并计算出总分和平均分
import xlwt
book = xlwt.Workbook()
sheet = book.add_sheet('score')
list = ['学号','姓名','语文成绩','数学成绩','英语成绩','总分','平均分']
score = {
"1":["小花",99,100,98.5],
"2":["小王",90,30.5,95],
"3":["小明",67.5,49.6,88]
}
for i in range(len(list)):
sheet.write(0,i,list[i])

for i,v in score.items(): #(行,列)
i = int(i)
num = i
name = v[0]
yuwen = v[1]
shuxue = v[2]
yingyu = v[3]
sum = yuwen+shuxue+yingyu
avrag = sum/3
sheet.write(i,0,num) #学号
sheet.write(i,1,name) #姓名
sheet.write(i,2,yuwen) #y语文成绩
sheet.write(i,3,shuxue) #数学成绩
sheet.write(i,4,yingyu) #英语成绩
sheet.write(i,5,sum)
sheet.write(i,6,avrag)
book.save('score.xls')

 

 

现有字符串a="Im Love python",需要变成b="python love Im"

a="Im Love python"
aa = (a.split(' '))[::-1]
print(aa)


将"wdnwjfwj we hd 9#sdfekfmew 2011"里的数字取出来相加结果为2020
import string
str = "wdnwjfwj we hd 9#sdfekfmew 2011"
for i in str.split(' ')[3]: #取出包含数字的段落(9#sdfekfmew)
number = string.digits #所有数字
if i in number:
res = int(i) + int((str.split(' ')[-1])) #9+2011
print(res)


posted @ 2017-12-03 21:56  13684995613  阅读(353)  评论(0编辑  收藏  举报