1.有如下字元串:n = "路飛學城"(程式設計題)
- - 将字元串轉換成utf-8的字元編碼的位元組,再将轉換的位元組重新轉換為utf-8的字元編碼的字元串
- - 将字元串轉換成gbk的字元編碼的位元組,再将轉換的位元組重新轉換為utf-8的字元編碼的字元串
n = '路飛學誠'
print(n.encode('utf-8'))
# b'\xe8\xb7\xaf\xe9\xa3\x9e\xe5\xad\xa6\xe8\xaf\x9a'
print(n.encode('utf-8').decode('utf-8'))
# 路飛學誠
print(n.encode('gbk'))
# b'\xc2\xb7\xb7\xc9\xd1\xa7\xb3\xcf'
print(n.encode('gbk').decode('gbk'))
# 路飛學誠
print(n.encode('gbk').decode('gbk').encode('utf-8'))
# b'\xe8\xb7\xaf\xe9\xa3\x9e\xe5\xad\xa6\xe8\xaf\x9a'
print(n.encode('gbk').decode('gbk').encode('utf-8').decode('utf-8'))
# 路飛學誠
2,讀檔案找到第9個字元,華 ,找到第二行的 實,删除最後一行 寫入檔案
桃之夭夭,灼灼其華。之子于歸,宜其室家。
桃之夭夭,有蕡其實。之子于歸,宜其家室。
桃之夭夭,其葉蓁蓁。之子于歸,宜其家人。
f = open('poem.txt', 'r+', encoding='utf-8')
f.seek(3*8)
print(f.read(1))
f.seek(3*28+2)
print(f.read(1))
data_list = f.readlines()
print(data_list)
data_list.pop()
print(data_list)
f.seek(0)
f.truncate()
f.write(''.join(data_list))
3,求出函數的執行時間,利用裝飾器
import time
def time_func(func):
def wrapper(*args,**kwargs):
time_start = time.time()
func(*args,**kwargs)
time_end = time.time()
print(time_end-time_start)
return wrapper
@time_func
def x(a,b):
time.sleep(1)
return a+b
x(1,8)
# 結果:1.0001220703125
帶參數的裝飾器
# 帶參數的裝飾器
import time
def show_timw(func):
def wrapper(a,b):
start_time = time.time()
ret = func(a,b)
end_time = time.time()
print("消耗時間為:%s" %(end_time-start_time))
return ret
return wrapper
@show_timw
def add(a,b):
time.sleep(1)
return a+b
print(add(48,45))
# 結果:
# 消耗時間為:1.0008337497711182
# 93
4.作用域
def test():
print(luffy)
luffy = "the king of sea."
test()
# 結果:the king of sea.
def test():
print(luffy)
luffy = 'e'
test()
luffy = "the king of sea."
test()
兩個test都會報錯,因為在定義變量之前已經調用變量了,是以錯誤
5,li = [1,2,3,5,5,6,7,8,9,9,8,3] 利用生成器功能,寫一個所有數值乘以2的功能
li = [1,2,3,5,5,6,7,8,9,9,8,3]
res = (i*2 for i in li)
# print(list(res))
# 結果:[2, 4, 6, 10, 10, 12, 14, 16, 18, 18, 16, 6]
# print(next(res))
# 結果:2(一次取一個值)
for i in res:
print(i)
# 結果:2
# 4
# 6
# 10
# 10
# 12
# 14
# 16
# 18
# 18
# 16
# 6
print(res.__next__())
# 結果:2
6.列印日志11/26/2017 10:44:21 PM bug 24 并寫入檔案example.log中
import logging
logging.basicConfig(filename='example.log', format='%(asctime)s - %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.DEBUG)
logging.warning('bug 24')
# 檔案内容:
# 03/24/2018 08:52:36 PM - bug 24
7,json和pickle
import json,pickle # json 可序列化的有 int str list tuple dict 沒有集合
# pickle 可序列化python所有資料類型包括函數 pickle 可序列化一些類 但類需要引用
li = [1,2,3]
dict = {1,2,3}
def fun():
return 3
str_data = json.dumps(li)
print(type(str_data),str_data)
# 結果:<class 'str'> [1, 2, 3]
list_data = json.loads(str_data)
print(list_data,type(list_data))
# 結果:[1, 2, 3] <class 'list'>
s = pickle.dumps(li)
print(s,type(s))
# 結果:b'\x80\x03]q\x00(K\x01K\x02K\x03e.' <class 'bytes'>
data = pickle.loads(s)
print(data,type(data))
# 結果:[1, 2, 3] <class 'list'>
with open('test.txt','w',encoding='utf-8') as f:
json.dump(li,f)
data = json.load(open('test.txt','r',encoding='utf-8'))
print(data,type(data))
# 結果:[1, 2, 3] <class 'list'>
pickle.dump(li,open('test1.txt','wb'))
data = pickle.load(open('test1.txt','rb'))
print(data,type(data))
# 結果:[1, 2, 3] <class 'list'>
pickle.dump(fun,open('test2.txt','wb'))
data = pickle.load(open('test2.txt','rb'))
print(data())
# 結果:3
8,閉包
def fun1():
n = 10
def fun2():
return n
return fun2
f=fun1()
print(f())
# 結果:10
9,生成器 疊代器
# 生成器:
s = (i for i in range(10))
print(next(s))
# 結果:0
# 疊代器:
def fun(n):
x=0
while(x<n):
yield x
x+=1
s = fun(3)
print(next(s))
print(s.__next__())
# 結果:0
# 1
from collections import Iterable,Iterator
print(isinstance({1,2,3},Iterable))
# 結果:True
s = iter([1,2,3,4,3,2,1])
print(s.__next__())
# 結果:
# 1
# 2
# 3
# 4
print(next(s))
# 結果:
# 1
# 2
# 3
# 4
for i in s:
print(i)
# 結果:
# 1
# 2
# 3
# 4
# 3
# 2
# 1
10,斐波那契數列
def fun(x):
n, a, b = 0, 0, 1
while n < x:
yield b
a, b = b, a + b
n += 1
結果:
res = fun(4)
# for i in res:
# print(i)
# 結果:1
# 1
# 2
# 3
print(next(res))
print(next(res))
print(next(res))
print(next(res))
print(next(res))
# 結果:1
# 1
# 2
# 3
# StopIteration
11,map filter globals() locals() hash()
print(globals())
# {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__':
# <_frozen_importlib_external.SourceFileLoader object at 0x0000017306D6B080>, '__spec__':
# None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>,
# '__file__':
# 'D:/exer.py', '__cached__': None}
print(locals())
# {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__':
# <_frozen_importlib_external.SourceFileLoader object at 0x0000017306D6B080>, '__spec__':
# None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>,
# '__file__': 'D:/exer.py', '__cached__': None}
n1=[1,2,3]
def fun():
n1[1] ='123'
return n1
print(fun())
# 結果:[1, '123', 3]
print('n1是什麼: ',n1)
# 結果:n1是什麼: [1, '123', 3]
res = map(lambda x:x*2,[1,2,3])
for i in res:
print(i)
# 結果:
# 2
# 4
# 6
print(list(res))
# 結果:[2, 4, 6]
res = filter(lambda x:x%2==0,list(range(10)))
# for i in res:
# print(i)
# 結果:
# 0
# 2
# 4
# 6
# 8
print(res.__next__())
# 結果: 0
print(next(res))
# 結果: 0
print(hash((1,2,3))) # 隻有 不可變的才可哈希 int str tuple 如:list dict set 不能被哈希
# 結果:2528502973977326415
12,三目 匿名 lambda
a = 2
b = 5
print(a if a>b else b)
# 結果:5
res =lambda a,b: a if a>b else b
print(res(2,3))
# 結果:3
fun = lambda x,y:x+y
print(fun(2,3))
# 結果:5
fun = lambda x,y:x if x>y else y
print(fun(2,3))
# 結果:3
res = map(lambda x:x*x,list(range(5)))
for i in res:
print(i)
# 結果:
# 0
# 1
# 4
# 9
# 16
fun = lambda x,y:x/y if x>y else x*y
print(fun(4,3))
# 結果:1.3333333333333333
13,time datetime
import time
import datetime
print(time.time())
# 結果:1521903163.3908226
print(time.asctime())
# 結果:Sat Mar 24 22:52:43 2018
print(time.gmtime())
# 結果:time.struct_time(tm_year=2018, tm_mon=3, tm_mday=24, tm_hour=14, tm_min=52, tm_sec=43, tm_wday=5, tm_yday=83, tm_isdst=0)
print(time.strftime('%Y-%m-%d %I:%M:%S %p',time.localtime()))
# 結果: 2018-03-24 10:52:43 PM
str_time =time.strftime('%Y-%m-%d %I:%M:%S %p',time.localtime())
# print(str_time)
# 結果:2018-03-24 10:52:43 PM
res = time.strptime(str_time,'%Y-%m-%d %I:%M:%S %p')
print(res)
# 結果:time.struct_time(tm_year=2018, tm_mon=3, tm_mday=24, tm_hour=22, tm_min=55, tm_sec=10, tm_wday=5, tm_yday=83, tm_isdst=-1)
print(time.mktime(res))
# 結果:1521903326.0
res =datetime.datetime.now() + datetime.timedelta(days=2,hours=3)
print(res)
# 結果:2018-03-27 01:55:43.520904
res1 = datetime.datetime.now().replace(year=2015,month=2,day=2)
print(res1)
# 結果:2015-02-02 22:55:58.174786
print(datetime.date.fromtimestamp(time.time()))
# 結果:2018-03-24
print(random.randint(1,3)) # 會包含3
print(random.randrange(1,3)) # 不會包含3
print(random.random())
print(random.choice('123123'))
14,random子產品
import random
print(random.randint(1,3)) # 會包含3
print(random.randrange(1,3)) # 不會包含3
print(random.random())
print(random.choice('123123'))
# 結果:
# 3
# 1
# 0.8458542042848031
# 1
import string
# digits:擷取所有的10進制數字字元
# punctuation:擷取所有的标點符号
# ascii_letters:擷取所有ascii碼中字母字元的字元串(包含大寫和小寫)
print(''.join(random.sample(string.digits+string.punctuation+string.ascii_letters,6)))
# 結果:.uim4D
li = list(range(10))
random.shuffle(li)
print(li)
# 結果: [5, 2, 1, 7, 6, 3, 4, 8, 0, 9]
15,os子產品
得到目前工作目錄,即目前Python腳本工作的目錄路徑: os.getcwd()
傳回指定目錄下的所有檔案和目錄名:os.listdir()
函數用來删除一個檔案:os.remove()
删除多個目錄:os.removedirs(r“c:\python”)
檢驗給出的路徑是否是一個檔案:os.path.isfile()
檢驗給出的路徑是否是一個目錄:os.path.isdir()
判斷是否是絕對路徑:os.path.isabs()
檢驗給出的路徑是否真地存:os.path.exists()
傳回一個路徑的目錄名和檔案名:os.path.split() e.g os.path.split('/home/swaroop/byte/code/poem.txt') 結果:('/home/swaroop/byte/code', 'poem.txt')
分離擴充名:os.path.splitext() e.g os.path.splitext('/usr/local/test.py') 結果:('/usr/local/test', '.py')
擷取路徑名:os.path.dirname()
獲得絕對路徑: os.path.abspath()
擷取檔案名:os.path.basename()
運作shell指令: os.system()
讀取作業系統環境變量HOME的值:os.getenv("HOME")
傳回作業系統所有的環境變量: os.environ
設定系統環境變量,僅程式運作時有效:os.environ.setdefault('HOME','/home/alex')
給出目前平台使用的行終止符:os.linesep Windows使用'\r\n',Linux and MAC使用'\n'
訓示你正在使用的平台:os.name 對于Windows,它是'nt',而對于Linux/Unix使用者,它是'posix'
重命名:os.rename(old, new)
建立多級目錄:os.makedirs(r“c:\python\test”)
建立單個目錄:os.mkdir(“test”)
擷取檔案屬性:os.stat(file)
修改檔案權限與時間戳:os.chmod(file)
擷取檔案大小:os.path.getsize(filename)
結合目錄名與檔案名:os.path.join(dir,filename)
改變工作目錄到dirname: os.chdir(dirname)
擷取目前終端的大小: os.get_terminal_size()
殺死程序: os.kill(10884,signal.SIGKILL)
16,sys子產品
sys.argv 指令行參數List,第一個元素是程式本身路徑
sys.exit(n) 退出程式,正常退出時exit(0)
sys.version 擷取Python解釋程式的版本資訊
sys.maxint 最大的Int值
sys.path 傳回子產品的搜尋路徑,初始化時使用PYTHONPATH環境變量的值
sys.platform 傳回作業系統平台名稱
sys.stdout.write('please:') #标準輸出 , 引出進度條的例子, 注,在py3上不行,可以用print代替
val = sys.stdin.readline()[:-1] #标準輸入
sys.getrecursionlimit() #擷取最大遞歸層數
sys.setrecursionlimit(1200) #設定最大遞歸層數
sys.getdefaultencoding() #擷取解釋器預設編碼
sys.getfilesystemencoding #擷取記憶體資料存到檔案裡的預設編碼
17,作用域,範圍
x = 10
def add(a, b=x):
return a + b
ret = add(10)
print(ret) # 輸出 20
x = 20
ret = add(10)
print(ret) # 輸出 20 不是30 注意子產品執行的流程 從上到下
18,lambda的應用
# 2.lambda 的應用
# ---CASE 1
fs = map(lambda i:(lambda j: i*j), range(6))
print([f(2) for f in fs])
#---CASE 2
fs = [lambda j:i*j for i in range(6)]
print([f(2) for f in fs])
#---CASE 3
fs = []
for i in range(6):
fs.append(lambda j:i*j)
if i==3:
break
print([f(2) for f in fs])
#---CASE 4
fs = [(lambda i:lambda j:i*j)(i) for i in range(6)]
print([f(2) for f in fs])
# 結果:
# [0, 2, 4, 6, 8, 10]
# [10, 10, 10, 10, 10, 10]
# [6, 6, 6, 6]
# [0, 2, 4, 6, 8, 10]
19,logging子產品有幾個日志級别?
總共有5個級别,預設級别是WARNING,
按照級别高低分别為CRITICAL ERROR WARNING INFO DEBUG
20,請配置logging子產品,使其在螢幕和檔案裡同時列印以下格式的日志
2017-10-18 15:56:26,613 - access - ERROR - account [1234] too many login attempts
# 20,請配置logging子產品,使其在螢幕和檔案裡同時列印以下格式的日志
# 2017-10-18 15:56:26,613 - access - ERROR - account [1234] too many login attempts
import logging
logger = logging.getLogger('mylog')
logger.level = logging.INFO
# 建立一個handler,用于寫入日志檔案
fh = logging.FileHandler('exer.log')
# 再建立一個handler,用于寫入輸出控制台
ch = logging.StreamHandler()
fh.level = logging.WARNING
ch.level = logging.ERROR
logger.addHandler(fh)
logger.addHandler(ch)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(lineno)s %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
logger.debug('too many login attempts')
logger.info('too many login attempts')
logger.warning('too many login attempts')
logger.error('too many login attempts')
logger.critical('too many login attempts')
21,json,pickle,shelve三個差別是什麼?
json:轉化的資料類型,int str list tuple dict 不支援set
json隻可以用于字元串或者字典等與python資料類型之間的序列化與反序列化之間的操作
pickle:支援python裡面所有的資料類型,隻能在python裡使用,函數也可以序列化
pickle可以用于python類有類型與python資料類型之間的序列化與反序列化的操作
shelve:pickle封裝了shelve,隻能在python裡使用,也就是說shelve對pickle進行了包裝,是一個鍵值對的形式,shelve子產品很簡單,隻有一個open函數
22,json的作用是什麼?
将記憶體的資料類型轉化為字元串,使其能存儲到硬碟上或者通過網絡傳輸到遠端,因為硬碟或者網絡傳輸隻接受bytes類型。
JSON不僅是标準格式,而且比XML更快,而且可以在web頁面直接讀取,非常友善。
23,subprocess執行指令方式有幾種?
三種執行指令的方法:
subprocess.run(*popenargs, input=None, timeout=None, check=False, **kwargs) #官方推薦
subprocess.call(*popenargs, timeout=None, **kwargs) #跟上面實作的内容差不多,另一種寫法
subprocess.Popen() #上面各種方法的底層封裝
24,為什麼要設計好目錄結構?
可讀性高: 不熟悉這個項目的代碼的人,一眼就能看懂目錄結構,知道程式啟動腳本是哪個
,測試目錄在哪兒,配置檔案在哪兒等等。進而非常快速的了解這個項目。
可維護性高: 定義好組織規則後,維護者就能很明确地知道,新增的哪個檔案和代碼應該放
在什麼目錄之下。這個好處是,随着時間的推移,代碼/配置的規模增加,項目結構不會混亂,
仍然能夠組織良好。
25,列印出指令行的第一個參數,例如:列印出 luffy
python argument.py luffy
26,代碼如下:
'''
Linux目前目錄/usr/local/nginx/html/
檔案名:index.html
'''
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(index.html)))
print(BASE_DIR)
列印的内容是什麼? nginx
os.path.dirname和os.path.abspath含義是什麼?
目錄名,絕對路徑
27,通過configparser子產品完成以下功能
檔案名my.ini
[DEFAULT]
[client]
port = 3306
socket = /data/mysql_3306/mysql.sock
[mysqld]
explicit_defaults_for_timestamp
port = 3306
socket = /data/mysql_3306/mysql.sock
back_log = 80
basedir = /usr/local/mysql
tmpdir = /tmp
datadir = /data/mysql_3306
default-time-zone = '+8:00'
- 修改時區 default-time-zone = '+8:00' 為 校準的全球時間 +00:00
- 删除 explicit_defaults_for_timestamp
- 為DEFAULT增加一條 character-set-server = utf8
# _*_ coding: utf-8 _*_
# 1.修改時區 default-time-zone = '+8:00' 為 校準的全球時間 +00:00
# 2.删除 explicit_defaults_for_timestamp
# 3.為DEFAULT增加一條 character-set-server = utf8
import configparser
# 建立ConfigParser執行個體
config = configparser.ConfigParser()
# 讀取配置檔案
res = config.read('my.ini')
print(res)
config.set('mysqld','default-time-zone ','+00.00')
config.write(open('my.ini','w'))
# 設定sections節點中,鍵名為options的值
config.remove_option('mysqld','explicit_defaults_for_timestamp')
config.write(open('my.ini','w'))
config.set('DEFAULT','character-set-server ','utf8')
config.write(open('my.ini','w'))
28,寫一個6位随機驗證碼程式(使用random子產品),要求驗證碼中至少包含一個數字、一個小寫字母、一個大寫字母.
# 10,寫一個6位随機驗證碼程式(使用random子產品),
# 要求驗證碼中至少包含一個數字、一個小寫字母、一個大寫字母.
import random
import string
# ascii_letters:擷取所有ascii碼中字母字元的字元串(包含大寫和小寫)
# digits:擷取所有的10進制數字字元
res = ''.join(random.sample(string.digits+string.ascii_letters,6))
# res = ''.join(random.sample(string.ascii_lowercase + string.digits, 6))
print(res)
29,利用正規表達式提取到 luffycity.com ,内容如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>luffycity.com</title>
</head>
<body>
</body>
</html>
# 11,利用正規表達式提取到 luffycity.com ,内容如下
import re
with open('str.txt','r',encoding='utf-8') as f:
data = f.read()
print(data)
res = re.search('\w+\.com',data).group()
print("結果 ",res)
30,寫一個使用者登入驗證程式,檔案如下:1234.json
{"expire_date": "2021-01-01", "id": 1234, "status": 0, "pay_day": 22, "password": "abc"}
- 使用者名為json檔案名,密碼為 password。
- 判斷是否過期,與expire_date進行對比。
- 登陸成功後,列印“登陸成功”,三次登陸失敗,status值改為1,并且鎖定賬号。
# 12,寫一個使用者登入驗證程式,檔案如下:1234.json
# {"expire_date": "2021-01-01", "id": 1234, "status": 0, "pay_day": 22, "password": "abc"}
#
# 使用者名為json檔案名,密碼為 password。
# 判斷是否過期,與expire_date進行對比。
# 登陸成功後,列印“登陸成功”,三次登陸失敗,status值改為1,并且鎖定賬号。
import os
import json
import time
def user_login():
retry_count = 0
while retry_count<3:
account = input('\033[32;1mplease input Acount:\033[0m').strip()
password = input('\033[32;1mplease input Password:\033[0m').strip()
load_file(account)
access_auth(account,password)
retry_count += 1
else:
update_file(account)
def access_auth(account,password):
account_data = load_file(account)
if account_data['status'] == 0:
if account_data['password'] == password:
expire_time = time.mktime(time.strptime(account_data['expire_date'],'%Y-%m-%d'))
if time.time() > expire_time: #如果信用卡已經過期,目前時間戳大于國企的時間戳
print("\033[31;1mAccount %s had expired,Please contract the bank"%account)
exit()
else: #信用卡未過期,傳回使用者資料的字典
return account_data
else:
print("\033[31;1mAccount or Passwordoes not correct!\033[0m")
else:
print("\033[31;1mAccount already be lock\033[0m")
exit()
def load_file(account):
file_name = '%s.json'%account
if os.path.isfile(file_name):
with open(file_name,'r',encoding='utf-8') as f:
acc_data = json.load(f)
return acc_data
else:
print("file [%s] does not exist"%account)
exit()
def update_file(account):
account_data = load_file(account)
print(account_data)
account_data['status'] =1
print(account_data)
file_name = '%s.json' % account
with open(file_name, 'w', encoding='utf-8') as f:
acc_data = json.dump(account_data, f)
user_login()
import json,time
count = 0
data = json.load(open('1234.json','r',encoding='utf-8'))
_username = '1234.json'
_password = data['password']
time_json = time.mktime(time.strptime(data['expire_date'],'%Y-%m-%d'))
time_now = time.time()
while count < 3:
if data['status'] == 1:
print('賬号已鎖定!')
break
elif time_now > time_json:
print('賬号已過期!')
break
else:
name = input('name:').strip()
password = input('password:').strip()
if name == _username and password == _password:
print('登入成功!')
break
else:
print('請重新輸入')
count += 1
else:
data['status'] = 1
json.dump(data,open('1234.json','w',encoding='utf-8'))
31,把第30題三次驗證的密碼進行hashlib加密處理。即:json檔案儲存為md5的值,然後用md5的值進行驗證
{"expire_date": "2019-03-01", "id": 1234, "status": 0, "pay_day": 22, "password": "900150983cd24fb0d6963f7d28e17f72"}
import json,time,hashlib
count = 0
data = json.load(open('1234.json','r',encoding='utf-8'))
_username = '1234.json'
_password = data['password'] #abc
time_json = time.mktime(time.strptime(data['expire_date'],'%Y-%m-%d'))
time_now = time.time()
while count < 3:
if data['status'] == 1:
print('賬号已鎖定!')
break
elif time_now > time_json:
print('賬号已過期!')
break
else:
name = input('name:').strip()
password = input('password:').strip()
if name == _username:
m = hashlib.md5()
m.update(password.encode())
if m.hexdigest() == _password:
print('登入成功!')
break
else:
print('請重新輸入')
count += 1
else:
data['status'] = 1
json.dump(data,open('1234.json','w',encoding='utf-8'))
32,最近luffy買了個tesla,通過轉賬的形式,并且支付了5%的手續費,tesla價格為75萬。檔案為json,請用程式實作該轉賬行為。
需求如下:
(1) 目錄結構為:
.
├── account
│ ├── luffy.json
│ └── tesla.json
└── bin
└── start.py
當執行start.py時,出現互動視窗
------- Luffy Bank ---------
1. 賬戶資訊
2. 轉賬
- 選擇1 賬戶資訊 顯示luffy的目前賬戶餘額。
- 選擇2 轉賬 直接扣掉75萬和利息費用并且tesla賬戶增加75萬
33,對上題增加一個需求:提現。,目錄結構如下:
.
├── account
│ └── luffy.json
├── bin
│ └── start.py
└── core
└── withdraw.py
當執行start.py時,出現互動視窗
------- Luffy Bank ---------
1. 賬戶資訊
2. 提現
- 選擇1 賬戶資訊 顯示luffy的目前賬戶餘額和信用額度。
- 選擇2 提現 提現金額應小于等于信用額度,利息為5%,提現金額為使用者自定義。
34,嘗試把上一章的驗證使用者登陸的裝飾器添加到提現和轉賬的功能上。
35,對第34題的使用者轉賬、登入、提現操作均通過logging子產品記錄日志,日志檔案位置如下
.
├── account
│ └── luffy.json
├── bin
│ └── start.py
└── core
| └── withdraw.py
└── logs
└── bank.log
30-35題的答案見:http://www.cnblogs.com/wj-1314/p/7501455.html
36,簡述ascii,unicode,utf-8,gbk之間的關系
unicode 包含所有國家的字元編碼
utf-8 可變長的字元編碼,英文表示一個位元組,中文表示三個位元組
ascii 美國标志資訊交換代碼,是基于拉丁字母的一套電腦編碼系統。
主要用于顯示現代英語和其他西歐語言,一個字元占一個位元組
gbk 全稱,漢字内碼擴充規範,一個字元占用兩個位元組
37,閱讀代碼,請寫出執行結果
1 a = "alex"
2 b = a.capitalize()
3 print(a)
4 print(b)
執行結果:
1 alex
2 Alex
38,寫代碼,有如下變量,請按照要求實作每個功能
name="aleX"
- a.移除 name 變量對應的值兩邊的空格,并輸入移除後的内容
- b.判斷 name 變量對應的值是否以"al"開頭,并輸出結果
- c.判斷 name 變量對應的值是否以"X"結尾,并輸出結果
- d.将 name 變量對應的值中的“l”替換為“p”,并輸出結果
- e.将 name 變量對應的值根據“l”分割,并輸出結果。
- f.請問,上一題e分割之後得到值是什麼類型(可選)
- g.将 name 變量對應的值變大寫,并輸出結果
- h.将 name 變量對應的值變小寫,并輸出結果
- i.請輸出 name 變量對應的值的第 2 個字元?
- j.請輸出 name 變量對應的值的前 3 個字元?
- k.請輸出 name 變量對應的值的後 2 個字元?
- l.請輸出 name 變量對應的值中“e”所在索引位置?
- m.擷取子序列,僅不包含後一個字元。如:oldboy則擷取oldbo;root則擷取roo
a.移除 name 變量對應的值兩邊的空格,并輸入移除後的内容
print(name.strip()) #aleX
b.判斷 name 變量對應的值是否以"al"開頭,并輸出結果
print(name.startswith('al')) #False
c.判斷 name 變量對應的值是否以"X"結尾,并輸出結果
print(name.endswith('X')) #False
d.将 name 變量對應的值中的“l”替換為“p”,并輸出結果
print(name.replace('l','p')) #apeX
e.将 name 變量對應的值根據“l”分割,并輸出結果。
print(name.split('l')) #['a', 'eX']
f.請問,上一題e分割之後得到值是什麼類型(可選)
print(type(name.split('l'))) #<class 'list'>
g.将 name 變量對應的值變大寫,并輸出結果
print(name.upper()) #ALEX
h.将 name 變量對應的值變小寫,并輸出結果
print(name.lower()) #alex
i.請輸出 name 變量對應的值的第 2 個字元?
print(name[1:2]) #l
j.請輸出 name 變量對應的值的前 3 個字元?
print(name[:3]) #ale
k.請輸出 name 變量對應的值的後 2 個字元?
print(name[-2:]) #eX
l.請輸出 name 變量對應的值中“e”所在索引位置?
print(name.index('e')) #2
m.擷取子序列,僅不包含後一個字元。如:oldboy則擷取oldbo;root則擷取roo
n1 = "oldboy"
n2 = n1.strip('y')
print(n2) #oldbo
39,字元串是否可以疊代對象?如可以請使用for循環每一個元素?
是
name = 'study'
for i in name:
print(i)
# 結果:
# s
# t
# u
# d
# y
40,什麼是疊代?
利用for循環來周遊一個清單(list)或元祖(tuple),将值依次取出,這種方法我們稱為疊代
利用for語句疊代字元串,建立一個字元串,name = "deidai",然後用for語句進行疊代。
41,請用代碼實作:
a,利用下劃線将清單的每一個元素拼接成字元串,strr="alexericrain"
strr = "alexericrain"
pinjie = '_'.join(strr)
print(type(pinjie),pinjie)
# <class 'str'> a_l_e_x_e_r_i_c_r_a_i_n
b.利用下劃線将清單的每一個元素拼接成字元串,li=['alex','eric','rain']
li = ['alex','eric','rain']
pinjie = '_'.join(li)
print(type(pinjie),pinjie)
# <class 'str'> alex_eric_rain
42,開發敏感詞語過濾程式,提示使用者輸入内容,如果使用者輸入的内容中包含特殊的字元:
如:"蒼老師"“東京熱”,則将内容替換為***
sentence_input = input("請輸入:")
sensitive_varcabulary1 = str.maketrans("蒼老師",'***')
sensitive_varcabulary2 = str.maketrans("東京熱",'***')
new_sentence = sentence_input.translate(sensitive_varcabulary1).translate(sensitive_varcabulary2)
print(new_sentence)
# 請輸入:dads大大的蒼老師
# dads大大的***
43, 請分别介紹檔案操作中不同的打開方式之間的差別:
44,什麼是裝飾器?寫一個裝飾器,可以列印輸出方法執行時長的資訊。
裝飾器模式(Decorator Pattern)允許向一個現有的對象添加新的功能,同時又不改變其結構。這種類型的設計模式屬于結構型模式,它是作為現有的類的一個包裝。
這種模式建立了一個裝飾類,用來包裝原有的類,并在保持類方法簽名完整性的前提下,提供了額外的功能。
我們通過下面的執行個體來示範裝飾器模式的用法。其中,我們将把一個形狀裝飾上不同的顔色,同時又不改變形狀類。
import time
def timer(func):
def decor(*args):
start_time = time.time()
func(*args)
end_time = time.time()
d_time = end_time - start_time
print("run the func use : ", d_time)
return decor
@timer #printSth = timer(printSth) -> printSth = decor
def printSth(str, count):
for i in range(count):
print("%d hello,%s!"%(i,str))
printSth("world", 1000000)#run the func use : 4.414000034332275
45:編寫3個函數,每個函數執行的時間是不一樣的,
提示:可以使用time.sleep(2),讓程式sleep 2s或更多,
46:編寫裝飾器,為每個函數加上統計運作時間的功能
提示:在函數開始執行時加上start=time.time()就可紀錄目前執行的時間戳,函數執行結束後在time.time() - start就可以拿到執行所用時間
47:編寫裝飾器,為函數加上認證的功能,即要求認證成功後才能執行函數
48:編寫裝飾器,為多個函數加上認證的功能(使用者的賬号密碼來源于檔案),要求登入成功一次,後續的函數都無需再輸入使用者名和密碼
提示:從檔案中讀出字元串形式的字典,可以用eval('{"name":"egon","password":"123"}')轉成字典格式
49,判斷下列資料類型是可疊代對象or疊代器
s='hello'
l=[1,2,3,4]
t=(1,2,3)
d={'a':1}
set={1,2,3}
f=open('a.txt')
s='hello' #字元串是可疊代對象,但不是疊代器
l=[1,2,3,4] #清單是可疊代對象,但不是疊代器
t=(1,2,3) #元組是可疊代對象,但不是疊代器
d={'a':1} #字典是可疊代對象,但不是疊代器
set={1,2,3} #集合是可疊代對象,但不是疊代器
f=open('test.txt') #檔案是可疊代對象,但不是疊代器
#如何判斷是可疊代對象,隻有__iter__方法,執行該方法得到的疊代器對象。
# 及可疊代對象通過__iter__轉成疊代器對象
from collections import Iterator #疊代器
from collections import Iterable #可疊代對象
print(isinstance(s,Iterator)) #判斷是不是疊代器
print(isinstance(s,Iterable)) #判斷是不是可疊代對象
#把可疊代對象轉換為疊代器
print(isinstance(iter(s),Iterator))
50,字元串“Luffy”,将小寫字母全部轉換成大寫字母,将大寫字幕轉換成小寫字幕,然後輸出到一個磁盤檔案"test"中儲存。
info = 'Luffy'
res = info.swapcase()
f = open('test1.txt','w',encoding='utf-8')
f.write(res)
f.close()
51,Python中print(__doc__)的作用
作用:輸出檔案開頭注釋的内容
舉例:
momodule.py
"""This is the module docstring."""
def f(x):
"""This is the function docstring."""
return 2 * x
執行
>>> import mymodule
>>> mymodule.__doc__
'This is the module docstring.'
>>> mymodule.f.__doc__
'This is the function docstring.'
不經一番徹骨寒 怎得梅花撲鼻香