1.讀取一個文件,顯示除了井號(#)開頭的行意外的所有行
# -*- coding: utf-8 -*-
"""
Created on Tue May 28 09:37:08 2019
@author: Omega_Sendoh
"""
#打開文件
f = open("install-sh","r")
#讀取文件的所有行,以列表形式存儲,每行為列表中的一個字符串元素
res = f.readlines()
#循環整個列表,去除以空格開頭的行的空格,然后去除以#號開頭的行的#號
for i in res:
if i[0] == "#":
continue
else:
print(i)
2.無重復字符的最長子串
# -*- coding: utf-8 -*-
"""
Created on Tue May 28 10:57:55 2019
@author: Omega_Sendoh
"""
"""
定義一個空的字符串,從起始位置開始搜索輸入的字符串,如果字符沒有出現在wind中,則把字符加入wind
如果字符出現在wind中,則找到字符串中出現該相同字符的位置,刪除該重復字符之前的所有字符
并重新加入該字符
"""
def LongestString(s):
wind = ''
l=0
for i in s:
if i not in wind:
wind +=i
l=max(l,len(wind))
else:
wind = wind[wind.index(i)+1:] + i
return l
s=input('enter string:')
print(LongestString(s))
3.制作一個密碼簿,其可以存儲一個網址,和一個密碼,請編寫程序完成這個密碼簿的增刪改查功能,并且實現文件存儲功能。
import json
def add_info():
#打開存儲文件,判斷文件中是否有內容
with open('usr.json','a+') as f:
info = f.read()
#如果沒有內容,創建一個字典,以字典的方式存儲網址與密碼
if not info:
with open('usr.json','a+') as f:
full_info = {}
net_add = input('enter your URL:')
passwd = input('enter your password:')
full_info[net_add] = passwd
print('add success')
json.dump(full_info,f)
#若文件中有內容,則把文件中的內容轉換為python的字典類型
else:
with open('usr.json','r') as f :
full_info = json.load(f)
#print((full_info))
net_add = input('enter your URL:')
passwd = input('enter your password:')
full_info.setdefault(net_add,passwd)
print('add success')
#給字典中添加對象,再次寫入文件中(即添加新的信息后重新更新文件的內容)
with open('usr.json','w') as f :
json.dump(full_info,f)
def del_info():
with open('usr.json','r') as f:
full_info = json.load(f)
#輸入想要刪除的網址
net_add = input('enter your delete URL:')
#如果該網址存在,則刪除網址與密碼,把更改后的數據存到文件中
if net_add in full_info:
del full_info[net_add]
print('delete success')
with open('usr.json','w') as f:
json.dump(full_info,f)
#若該網址不存在,提示網址不存在
else:
print('This URL not exist')
def change_info():
with open('usr.json','r') as f:
full_info = json.load(f)
#輸入要更改的網址與密碼
net_add = input('enter your change URL:')
passwd = input('enter your new password:')
if net_add in full_info:
full_info[net_add] = passwd
print('change password succcess')
with open('usr.json','w') as f:
json.dump(full_info,f)
else:
print('This URL not exist')
def check_info():
with open('usr.json','r') as f:
full_info = json.load(f)
net_add = input('enter your check URL:')
if net_add in full_info:
print('This URL password is:',full_info[net_add])
else:
print('This URL not exist')
print('you can choose: add/del/change/check/quit')
while 1:
obj = input('enter your choose:')
if obj == 'add':
add_info()
elif obj == 'del':
del_info()
elif obj == 'change':
change_info()
elif obj == 'check':
check_info()
else:
break
運行結果: