pract
1 # -*- coding:utf-8 -*-
2 # Author:Sure Feng
3
4 # print(-6 or 2 > 1) # -6
5 # print(6 and 2 > 1) # True
6 # print(not 9) # False
7 #
8 # while -9.8:
9 # print("9")
10 # break
11
12
13 # print("====練習5、求1-2+3-4+5 ... 99中除88之外的所有數的和====")
14 # t9 = 0
15 # count = 0
16 # while t9 < 99:
17 # t9 += 1
18 # if t9 == 88:
19 # continue
20 # elif t9 % 2 == 0:
21 # count = count - t9
22 # else:
23 # count = count + t9
24 # else:
25 # print(count)
26
27 # v = 8
28 # d = v.bit_length()
29 # print(d)
30
31
32 # if -9:
33 # print("ok")
34 # else:
35 # print("NG")
36
37
38 # str = "我愛北京天安門"
39 # print(str[0])
40 # print(str[1])
41 # print(str[2])
42 # print(str[3])
43 # print(str[4])
44 # a1="dqsddsfs"
45 # ret2 = a1.center(20,"*")
46 # print(ret2)
47
48 # #split 以什么分割,最終形成一個列表此列表不含有這個分割的元素。
49 # ret9 = 'title,Tilte,atre,'.split('t',1)
50 # print(ret9)
51 # ret91 = 'title,Tilte,atre,'.rsplit('t',1)
52 # print(ret91)
53
54 # msg="abc DEF ghI"
55 # print(msg.title())
56
57 # #format的三種玩法 格式化輸出
58 # print('{} {} {}'.format('egon',18,'male'))
59 # print('{1} {0} {1}'.format('egon',18,'male'))
60 # print('{name} {age} {sex}'.format(sex='male',name='egon',age=18))
61
62 # res='{} {} {}'.format('egon',18,'male')
63 # res='{1} {0} {1}'.format('egon',18,'male')
64 # res='{name} {age} {sex}'.format(sex='male',name='egon',age=18)
65
66
67 # #strip
68 # name='*egon**'
69 # print(name.strip('*'))
70 # print(name.lstrip('*'))
71 # print(name.rstrip('*'))
72
73
74 #replace
75 # name='alex say :i have onealex tesla,my name is alex'
76 # print(name.replace('alex','SB',2))
77
78 # name='abcafjjdaabcjdfajaabcjejiafj'
79 # print(name.replace('abc','***',2))
80
81 # li = [1,'a','b',2,3,'a']
82 # li.insert(0,55) #按照索引去增加
83 # print(li)
84 #
85 # li.append('aaa') #增加到最后
86 # li.append([1,2,3]) #增加到最后
87 # print(li)
88 #
89 # li.extend(['q,a,w']) #迭代的去增
90 # print(li)
91 # li.extend(['q,a,w','aaa'])
92 # print(li)
93 # li.extend('a')
94 # print(li)
95 # li.extend('abc')
96 # print(li)
97 # li.extend('a,b,c')
98 # print(li)
99
100 li = [1,'m','b',2,3,'a']
101 # l1 = li.pop(1) #按照位置去刪除,返回去除成功的值
102 # print(l1)
103 #
104 # del li[1:3] #按照位置去刪除,也可切片刪除,沒有返回值。
105 # print(li)
106
107 # li.remove(1) #按照元素去刪除一個
108 # print(li)
109
110 # li.clear() #清空列表
111
112 # # 改
113 # li = [1,'a','b',2,3,'a']
114 # li[1] = 'dfasdfas'
115 # print(li)
116 # li[1:4] = ['a','b']
117 # print(li)
118
119 # #增
120 # d = {}
121 # d['s'] = [1,2,3] # dic[key] = value , key一定是不可變對象
122 # print(d) #{'s': [1, 2, 3]}
123 # d.setdefault('o') #在字典中添加鍵值對,如果只有鍵那對應的值是none
124 # print(d) #{'s': [1, 2, 3], 'o': None}
125 # d.setdefault(4,'s') #在字典中添加鍵值對
126 # print(d) #{'s': [1, 2, 3], 'o': None, 4: 's'}
127 # d.setdefault(4,'ww')#如果原字典中存在設置的鍵值對,則他不會更改或者覆蓋
128 # print(d) #{'s': [1, 2, 3], 'o': None, 4: 's'}
129
130
131 # dic['li'] = ["a","b","c"]
132 # print(dic)
133 # # setdefault 在字典中添加鍵值對,如果只有鍵那對應的值是none,但是如果原字典中存在設置的鍵值對,則他不會更改或者覆蓋。
134 # dic.setdefault('k','v')
135 # print(dic) # {'age': 18, 'name': 'jin', 'sex': 'male', 'k': 'v'}
136 # dic.setdefault('k','v1') # {'age': 18, 'name': 'jin', 'sex': 'male', 'k': 'v'}
137 # print(dic)
138
139 # d = {'age': 18, 'name': 'jin', 'sex': 'male', 'k': 'v'}
140 # dic_pop = d.pop('a','沒有時的返回值') # pop根據key刪除鍵值對,并返回對應的值,如果沒有key則返回默認返回值
141 # print(dic_pop)
142 # del d["name"] # 沒有返回值。
143 # print(d)
144 #
145 # dic_pop1 = d.popitem() # 隨機刪除字典中的某個鍵值對,將刪除的鍵值對以元祖的形式返回
146 # print(dic_pop1) # ('name','jin')
147 # print(d)
148 #
149 # dic_clear = d.clear() # 清空字典,返回值為None
150 # print(d,dic_clear) # {} None
151
152 # d = {}
153 # d['s'] = [1,2,3] # dic[key] = value , key一定是不可變對象
154 # print(d)
155 # d['s'][1]='ut'
156 # print(d)
157
158
159 # dic = {"name":"jin","age":18,"sex":"male", 'k':[1,2,3]}
160 # dic2 = {"name":"alex","weight":75}
161 # dic.update(dic2)# 將dic所有的鍵值對覆蓋添加(相同的覆蓋,沒有的添加)到dic2中
162 # print(dic) #{'name': 'alex', 'age': 18, 'sex': 'male', 'weight': 75}
163 # dic['name'] = 'sure'
164 # dic['l'][1] = 'dfa'
165 # print(dic) #{'name': 'sure', 'age': 18, 'sex': 'male', 'weight': 75}
166
167
168 # item = dic.items()
169 # print(item,type(item)) # dict_items([('name', 'jin'), ('sex', 'male'), ('age', 18)]) <class 'dict_items'>
170 # # 這個類型就是dict_items類型,可迭代的
171 #
172 # keys = dic.keys()
173 # print(keys,type(keys)) # dict_keys(['sex', 'age', 'name']) <class 'dict_keys'>
174 #
175 # values = dic.values()
176 # print(values,type(values)) # dict_values(['male', 18, 'jin']) <class 'dict_values'> 同上
177
178 # for i in enumerate('fjalfjadlfjla'):
179 # print(i) #(0, 'f') (1, 'j') ...
180 # for i, j in enumerate('fjalfjadlfjla',4):
181 # print(i,j) #4 f 5 j ...
182
183 # for i in range(2, 10, 2):
184 # print(i) # 2 4 6 8
185
186 name = input("name:")
187 password = int(input("password:"))
188 dic = {'s':[1, 3]}
189
190 while True:
191 if name in dic:
192 my_password = dic[name][0]
193 count = dic[name][1]
194 # password = int(input("password:"))
195 if password == my_password:
196 print("登錄成功!")
197 dic[name][1] = 3
198 break
199 else:
200 if count >1:
201 print(count)
202 count -= 1
203 dic[name][1] = count # 調了很久的bug,沒賦值啊
204 print(count)
205 print("密碼錯誤,您還可嘗試%d次" % count)
206 password = int(input("password:"))
207 else:
208 print("密碼錯誤次數超3次,賬戶已被鎖定")
209 break
210 else:
211 dic[name] = password
212 print("登錄成功")
213 break test 1 # Author:Sure Feng
2
3
4 '''
5 從新出發,希望這次能一學到底~~
6 把吸收到的、當時的理解定時輸出,不怕失誤,持續改進
7
8
9 計算機基礎小知識:
10 CPU:運行機器碼文件,相當于人類大腦,用于計算
11 內存:暫存數據的地方,成本高斷電數據即消失。如2G(公司的電腦)、4G(現在的電腦)、8G、16G、32G
12 硬盤:永久存儲數據的地方
13 操作系統:運行程序時,把相應機器碼放入內存,CPU執行
14 應用程序,就是應用程序
15
16
17 一、Python的初步了解
18 Python他爹:
19 吉多·范羅蘇姆(Guido van Rossum),中文名龜叔。Python這門語言是他在一個無聊的
20 圣誕節打發時間寫出來的。(不禁感嘆,天才啊~~自能能在半年學會就感謝上蒼了)。
21
22 Python定位:優美、清晰、簡單。2017年7月的TIOBE排行榜第四
23
24 Python的主要應用:
25 數據爬蟲&分析、金融量化(前兩項是學習Python的動力,投資的利器)、人工智能&科學運算、WEB開發、
26 圖形GUI、系統運維。全球各大網站的應用(知乎、豆瓣、谷歌等)
27 Python發展史中的重要節點2008,同時推出Python2.6和Python3.0。November 2014宣布Python2.7版本將剛在
28 2020年停止支持。(當初還糾結是學2.7還是3.5。。。)
29
30 為什么推出Python3?
31 Python2源碼重復率高,不規范,與Python當初定位不相符(優美、清晰、簡單),顧創建了Python3。
32
33 Python2和3是不兼容的,體現在很多方面:
34 1、默認編碼:Python2是ascii碼,Python3是utf-8。(解釋器在加載 .py 文件中的代碼時,會對內容進行編碼)
35 編碼亂碼問題:在首行注明:-*- coding:utf-8 -*-
36 ASCII碼:最早的一套基于拉丁字母的電腦編碼,用8位來表示(一個字節),最多能表示2**8 = 256個符號
37 Unicode(統一碼、萬國碼、單一碼)是一種在計算機上使用的字符編碼。最少由16位來表示(2個字節),即:2^16 = 65536
38 UTF-8,Unicode的壓縮和優化,ascii碼(1個字節)、歐洲(2個字節),東亞(3個字節)
39 2、(后續補上)
40
41 Python是一種動態的解釋型強類型語言。在命令行下運行python就是啟動CPython解釋器。
42 人類與機器間語言不一樣,人類的語言()中文、英文等),機器CPU執行的語言(二進制文件)。
43 編譯型語言(開發效率低,不能跨平臺,運行速度快),c、c++
44 人能讀懂的代碼→編譯,獲的機器碼(如xxx.exe文件)→CPU運行。
45 解析型語言(開發效率高,能跨平臺,運行速度相對慢,但是對用戶而言并沒差別),如Python、JavaScript、PHP
46 人能讀懂的代碼→解析器解析.py文件(默認CPython,C語言寫的)→獲得相應的字節碼→通過虛擬機邊執行邊翻譯→CPU運行。
47 動態語言:編程時不需要指定數據類型,在運行期間才去做數據類型的檢查。
48 靜態語言:編程時需要指定數據類型,在編譯時會做數據類型的檢查。
49 強類型定義語言:變量被指定了某個數據類型,如果不經過強制轉換,就永遠是這個數據類型
50 弱類型定義語言:數據類型可以被忽略的語言。它與強類型定義語言相反, 一個變量可以賦不同數據類型的值
51 Python運行:終端→命令行(cmd、PowerShell)→cd切換到目標路徑, Python 文件名.py
52
53 注釋:
54 當行注釋:# ctrl+/
55 多行注釋:''' ''' """ """
56 '''
57
58 '''
59 報錯收集:
60 1、TypeError: can only concatenate str (not "list") to str
61 2、TypeError: not enough arguments for format string ,字符串占位符寫少了
62 3、SyntaxError: invalid syntax , Python3不支持<>,改用!=
63 4、ValueError: unsupported format character '%' (0x25) at index 2 使用占位符時,若想打印%,需寫%%轉義
64
65 '''
66
67
68 '''
69 變量:聲明變量,數據的門牌號,代指內存里某個地址中保存的內容
70 命名規則:
71 允許:有可描述性,由字母、數字、下劃線組成
72 不允許:第一個字符不能是數字、關鍵字
73 不好的:變量名過長、帶中文、拼音、詞不達意
74 '''
75 #推薦一:駝峰體
76 AgeOfOldboy = 56
77 #推薦二:下劃線
78 age_of_oldboy = 56
79
80
81 # 變量的賦值:
82 # 實驗一,變量名指向數字、字符串時,c通過b找到對象1,隨后無論ab怎么變,均不改變c的指向,c=1
83 a = 1
84 b = a
85 a = "hello,python"
86 c = b
87 b = 5
88 print("a=", a, ", b=", b, ", c=", c) # a= hello,python , b= 5 , c= 1
89
90 # 實驗二,d通過l找到列表對象,實際為一存儲地址,不涉及內部數據,所以僅當內部數據改變時,打印的數據相應改變。
91 # e指向列表中的字符串1,實際是通過列表l找到對象“1”,之后就與列表沒關系了,所以不會隨列表而改變
92 l = ["1", 2, "python"]
93 d = l
94 e = l[0]
95 print("l=", l, ", d=", d, ", e=", e) # l= ['1', 2, 'python'] , d= ['1', 2, 'python'] , e= 1
96 l[0] = 56
97 print("l=", l, ", d=", d, ", e=", e) # l= [56, 2, 'python'] , d= [56, 2, 'python'] , e= 1
98
99
100 '''
101 常量:指不會變或過程中不會改變的量
102 命名方式:全大寫
103 注意:Python中沒有機制強制規定不能改,更改也不會報錯
104 '''
105 MY_AGE = 18
106
107
108 # 程序交互:用戶有參與感的操作,會適當進行一些數據輸入
109 # input接收的所有輸入默認都是字符串格式,可適當使用int(str)、str( yourStr )
110 # age = input("how old are you >>>") # how old are you >>>18
111 # print("oh,%d is wonderful" % int(age)) # oh,18 is wonderful
112
113
114 # 計算機的運算:算術運算、比較運算、邏輯運算、賦值運算、成員運算、身份運算、位運算(后三個以后學)
115 # 算術運算:+、 -、 *、 /、 %、 //、 **(即^)
116 print(10%3) # 1
117 print(10//3) # 3
118 print(2**2) # 4
119
120 # 比較運算:<, <=, >, >=, =, ==, !=或<>
121 t1 = 'hello'
122 t2 = 3
123 print(t1 == "hello") # True
124 # print(3 <> 3) # SyntaxError: invalid syntax ,不支持
125 print(3 != "hello") # True
126
127 # 賦值運算:=, +=, -=, *=, /=, %=, **=, //=
128 t3 = 2
129 t4 = 10
130 t3 += t4 # t3 = t3 + t4 = 2+10
131 print(t3) # 12
132 t3 -= t4 # t3 = t3 - t4 = 12-10
133 print(t3) # 2
134 t3 *= t4 # t3 = t3 * t4 = 2*10
135 print(t3) # 20
136 t3 /= t4 # t3 = t3 / t4 = 20/10
137 print(t3) # 2.0
138 t3 **= t4 # t3 = t3 ** t4 = 2**10
139 print(t3) # 1024.0
140 t3 %= t4 # t3 = t3 % t4 = 1024%10
141 print(t3) # 4.0
142
143 # 邏輯運算:and, or, not, 先級關系為( )>not>and>or
144 print(3>4 or 4<3 and 1==1) #False
145 print(1 < 2 and 3 < 4 or 1>2) #True
146 print(2 > 1 and 3 < 4 or 4 > 5 and 2 < 1) #True
147 print(1 > 2 and 3 < 4 or 4 > 5 and 2 > 1 or 9 < 8) #False
148 print(1 > 1 and 3 < 4 or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 6) #False
149 print(not 2 > 1 and 3 < 4 or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 6) #False
150 # x or y , x為真,值就是x,x為假,值是y;
151 # x and y, x為真,值是y,x為假,值是x
152 # 非0數字 == True, 0 == False
153 print(8 or 4) # 8
154 print(0 and 3) # 0
155 print(0 or 4 and 3 or 7 or 9 and 6) # 3
156 print(-6 or 2 > 1) # -6
157 print(6 and 2 > 1) # True
158 print(not 9) # False
159 # ,not in :判斷子元素是否在原字符串(字典,列表,集合)中:
160 print('喜歡' in 'dkfljadklf喜歡hfjdkas') #True
161 print('a' in 'bcvd') #False
162 print('y' not in 'ofkjdslaf') #True
163
164
165 '''
166 流程控制(if語句、while語句):在程序中預設判斷語句,讓程序往滿足相應條件的方向執行
167 強制縮進:讓程序知道每段代碼依賴的條件,確定相應的代碼塊區域
168 縮進原則:
169 1、頂級代碼必須頂行寫,即如果一行代碼本身不依賴于任何條件,那它必須不能進行任何縮進
170 2、同一級別的代碼,縮進必須一致
171 3、官方建議縮進用4個空格,當然你也可以用2個(但不規范)
172 '''
173
174 '''
175 流程控制之if 語句:滿足條件,就往下走
176 練習:匹配成績的小程序,成績有ABCDE5個等級,與分數的對應關系如下
177 A 90-100
178 B 80-89
179 C 60-79
180 D 40-59
181 E 0-39
182 要求用戶輸入0-100的數字后,你能正確打印他的對應成績
183 '''
184 # score_info = input("How many points do you have >>> ")
185 # # "負數".isdigit 為False
186 # if score_info.isdigit():
187 # score = int(score_info)
188 # if score > 100:
189 # print("天才了,最高才100分。。。")
190 # elif score >= 90:
191 # print("A")
192 # elif score >= 80:
193 # print("B")
194 # elif score >= 60:
195 # print("C")
196 # elif score >= 40:
197 # print("D")
198 # else:
199 # print("E")
200 # else:
201 # print("請輸入0~100分")
202
203
204 '''
205 流程控制之while語句:只要滿足條件,就不斷循環
206 無限循環:while True: 或者 while 1:
207 結束循環:
208 1、終結當次循環 continue
209 2、終結while循環 break
210 '''
211 # 練習:在0~30間,打印0~20間的能被3整除的數
212 count = 0
213 while count <= 30:
214 count += 1
215 if count % 3 != 0:
216 continue # 終結當次循環 continue
217 elif count > 20:
218 print("已超出范圍 0~20,不玩了")
219 break # 終結while循環 break
220 else:
221 print("count:",count)
222
223 '''
224 while else語句:while執行完成后,就執行else的內容。當被break中斷,就不執行else內容。
225 練習:電影后,用戶自行選擇是否想展示彩蛋
226 '''
227 # choice = input("電影結束還有5秒,想看彩蛋嗎?(Y/N)>>>")
228 # date = 5
229 # while date > 0:
230 # print("結束倒數:",date)
231 # date -= 1
232 # if date == 0:
233 # if choice == "N":
234 # print("電影結束")
235 # break
236 # else:
237 # print("電影結束,彩蛋來啦~")
238
239
240 '''
241 for循環:按順序循環遍歷可迭代對象(string/tuple/list/dict)
242 enumerate:枚舉,對于一個可迭代的(iterable)/可遍歷的對象(如列表、字符串)
243 range(start, end, args)
244 '''
245 for i in range(2, 10, 2):
246 print(i) # 2 4 6 8
247 for i in enumerate('fjalfjadlfjla'):
248 print(i) #(0, 'f') (1, 'j') ...
249 for i, j in enumerate('fjalfjadlfjla',4):
250 print(i,j) #4 f 5 j ...
251
252 print('''
253 相關練習題
254 ====練習1、使用while循環輸入 1 2 3 4 5 6 8 9 10====''')
255 t5 = 0
256 while t5 < 10:
257 t5 += 1 # 一定要在(t5 == 7)判斷前,否則出現死循環
258 if t5 == 7:
259 print(" ")
260 continue
261 print(t5)
262
263 print("====練習2、求1-100的所有數的和====")
264 t6 = 1
265 count = 0
266 while t6 <= 100:
267 count = count + t6
268 t6 += 1
269 else:
270 print(count)
271
272 print("====練習3、輸出 1-100 內的所有奇數====")
273 t7 = 0
274 while t7 <100:
275 t7 += 1
276 if t7 % 2 == 0:
277 continue
278 print(t7)
279
280 print("====練習4、輸出 1-100 內的所有偶數====")
281 t8 = 0
282 while t8 < 100:
283 t8 += 1
284 if t8 % 2 == 0:
285 print(t8)
286
287 print("====練習5、求1-2+3-4+5 ... 99中除88之外的所有數的和====")
288 t9 = 0
289 count = 0
290 while t9 < 99:
291 t9 += 1
292 if t9 == 88:
293 continue
294 elif t9 % 2 == 0:
295 count = count - t9
296 else:
297 count = count + t9
298 else:
299 print(count)
300
301 print("====練習6、用戶登陸(三次機會重試)====")
302 name = input("name:")
303 password = int(input("password:"))
304 dic = {'s':[1, 3]}
305
306 while True:
307 if name in dic:
308 my_password = dic[name][0]
309 count = dic[name][1]
310 # password = int(input("password:"))
311 if password == my_password:
312 print("登錄成功!")
313 dic[name][1] = 3
314 break
315 else:
316 if count >1:
317 print(count)
318 count -= 1
319 dic[name][1] = count # 調了很久的bug,沒賦值啊
320 print(count)
321 print("密碼錯誤,您還可嘗試%d次" % count)
322 password = int(input("password:"))
323 else:
324 print("密碼錯誤次數超3次,賬戶已被鎖定")
325 break
326 else:
327 dic[name] = password
328 print("登錄成功")
329 break Python基礎 new 1 # -*- coding:utf-8 -*-
2 # Author:Sure Feng
3
4 '''
5 Python的數據類型:
6 1、整數類型:32位、64位代表的字符數量,bit_length()
7 2、浮點類型:帶小數的
8 3、字符串類型:單行/多行打印,字符串的加法/乘法,格式化輸出(%s/%d),索引,切片,常用方法
9 4、布爾類型:正規寫法:1 == True, 0 == False | 實際上,非0數字 == True, 0 == False
10 5、列表list:類似于其他語言中的數組
11 6、字典dict
12 7、元組tuple:只讀列表,可被查詢,使用切片
13
14 總結:
15 按存儲空間的占用分(從低到高)
16 數字
17 字符串
18 集合:無序,即無序存索引相關信息
19 元組:有序,需要存索引相關信息,不可變
20 列表:有序,需要存索引相關信息,可變,需要處理數據的增刪改
21 字典:無序,需要存key與value映射的相關信息,可變,需要處理數據的增刪改
22
23 按存值個數區分
24 標量/原子類型:數字,字符串
25 容器類型:列表,元組,字典
26
27 按可變不可變區分
28 可變:列表,字典
29 不可變:數字,字符串,元組,布爾值
30
31 按訪問順序區分
32 直接訪問:數字
33 順序訪問(序列類型):字符串,列表,元組
34 key值訪問(映射類型):字典
35 '''
36
37
38 '''
39 1、數據類型--整數類型
40 在32位機器上,整數的位數為32位(-2**31~2**31-1),
41 在64位系統上,整數的位數為64位(-2**63~2**63-1),減一是為了減0
42 '''
43 v = 8 # 0000 1000
44 d = v.bit_length() # 十進制用二進制表示時,所需要的最小位數
45 print(d) # 4
46 print(type(23)) #<class 'int'>,沒有長整型long,均為int
47
48
49 '''
50 2、數據類型--浮點類型
51 '''
52 print(type(23.6)) #<class 'float'>
53
54
55 '''
56 3、數據類型--字符串類型
57 主要應用:索引、切片、常用方法、格式化輸出
58 '''
59 print(type("23")) #<class 'str'>
60 print("I'm sure,單雙號注意")
61 print("字"+"符"+"拼"+"接") # 字符間可拼接
62 print("字符" + "~"*2) # 字符數值間可乘積, 字符~~
63 print('''
64 多行打印
65 多行打印
66 多行打印
67 ''')
68
69 # 索引,依據角標,獲取相應的字符
70 str = "我愛北京"
71 print(str[0]) # 我
72 print(str[1]) # 愛
73 print(str[2]) # 北
74 print(str[3]) # 京
75
76 # 切片,字符串[索引:索引:步長],原則:顧頭不顧尾
77 s2 = "abcdefghijk"
78 print(s2[:3]) # abc, 開頭默認0開始
79 print(s2[1:]) # bcdefghijk, 默認取到尾部
80 print(s2[0:-1]) # abcdefghij, -1表示末尾
81 print(s2[-3:-1]) # ij
82 print(s2[2:10:3]) # cfi
83 print(s2[10:0:-3]) # kheb
84
85 # 字符串常用方法
86 s3 = "abc DEF ghI"
87 # 大小寫轉換
88 print(s3.capitalize()) # 首字母大寫 Abc def ghi
89 print(s3.swapcase()) # 大小寫翻轉 ABC def GHi
90 print(s3.title()) # 每個單詞的首字母大寫,其余小寫 Abc Def Ghi
91 # 調整填充格式
92 print(s3.center(20,"-")) #內容居中,設定總長度,在空白處填充指定字符 ----abc DEF ghI-----
93 s5 = "dsd a\t"
94 #默認將一個tab鍵變成8個空格,如果tab前面的字符8個唯一單位,長度不足則補全8個
95 print(s5.expandtabs()) # 若指定長度(需要大于字符串長度),則按指定長度補全
96 #strip 刪除指定字符
97 name='*egon**'
98 print(name.strip('*')) # 全部
99 print(name.lstrip('*'))
100 print(name.rstrip('*'))
101 #split 分割指定字符。以什么分割,最終形成一個列表此列表不含有這個分割的元素。
102 ret9 = 'title,Tilte,atre,'.split('t',1) # 從左邊開始,替換1個 ['', 'itle,Tilte,atre,']
103 print(ret9)
104 ret91 = 'title,Tilte,atre,'.rsplit('t',2)# 從右邊開始,替換2個 ['title,Til', 'e,a', 're,']
105 print(ret91)
106 #replace 替換指定字符,可選擇替換個數
107 name='abcafjjdaabcjdfajaabcjejiafj'
108 print(name.replace('abc','***',2)) # ***afjjda***jdfajaabcjejiafj
109 # 長度統計
110 s4 = "aaasdfvddradghsa"
111 print(s4.count("a",0,2)) #數字符串中的元素出現的個數,可切片,也是顧頭不顧尾 2
112 # 邏輯判斷類的方法
113 s6 = "werasdfvddradghpa"
114 print(s6.startswith("wer",2,9)) #判斷是否以...開頭 可切片,顧頭不顧尾 False
115 print(s6.endswith("hp", 0,-1)) #判斷是否以...結尾 True
116 print(s6.find("m",2,6)) # 返回的找到的元素的索引,如果找不到返回-1
117 print(s6.index("r")) #返回的找到的元素的索引,找不到報錯 ValueError: substring not found
118 #format的三種玩法 格式化輸出
119 print('{} {} {}'.format('a',"b","c")) # a b c
120 print('{2} {0} {1}'.format('a',"b","c")) #c a b
121 print('{name} {age} {sex}'.format(sex='male',name='egon',age=18)) #egon 18 male
122 #####is系列
123 name='jinxin123'
124 print(name.isalnum()) #字符串由字母或數字組成
125 print(name.isalpha()) #字符串只由字母組成
126 print(name.isdigit()) #字符串只由數字組成
127
128
129
130 '''
131 格式化輸出:%s就是代表字符串占位符,除此之外,還有%d,是數字占位符
132 使用事項:若想輸出%,需加%轉義,即%%,否則報錯
133 練習:問用戶的姓名、年齡、工作、愛好 ,然后打印成以下格式
134 ------------ info of surefeng -----------
135 Name : surefeng
136 Age : 18
137 job : student
138 Hobbie: cosmic
139 ------------- end -----------------
140 '''
141 # name = input("what's your name>>>")
142 # age = input("what's your age>>>")
143 # job = input("what's your job>>>")
144 # hobbie = input("what's your hobbie>>>")
145 # # 不能直接多行打印print(''' ''')的形式,內部的%s會被當做字符串處理
146 # info = '''
147 # ------------ info of %s -----------
148 # Name : %s
149 # Age : %s
150 # job : %s
151 # Hobbie: %s
152 # ------------- end -----------------
153 # ''' % (name, name, age, job, hobbie)
154 # print(info)
155
156
157 '''
158 4、數據類型--布爾類型
159 正規寫法:1 == True, 0 == False | 實際上,非0數字 == True, 0 == False
160 '''
161 print(type(2 > 5)) # <class 'bool'>, True,False
162
163
164 '''
165 5、列表list:
166 大量儲存數據的地方,同一列表中可存放不同類型的數據,有索引、切片
167 '''
168 l = [1, 'e', 't', 1, 'c']
169 # 增
170 l.append([1,3,5]) # 末尾添加
171 print(l)
172 l.insert(2,'y') # 指定位置增加
173 print(l)
174 l.extend('sfjj') #迭代增加
175 print(l)
176 # 刪
177 del l[1:3] #切片刪除,沒有返回值
178 print(l)
179 l.pop(7)#刪除指定索引的數據
180 print(l)
181 l.remove(1) #刪除第一個找到的數據
182 print(l)
183 # l.clear() #清除列表,慎用
184 print(l)
185 #改
186 l[2] = [2,'t,5',0]
187 print(l) #['t', 1, [2, 't,5', 0], [1, 3, 5], 's', 'f', 'j']
188 l[1:4] = ['s','b']# 賦值不夠就默認刪除了
189 print(l) #['t', 's', 'b', 's', 'f', 'j']
190 # 查
191 # 切片或遍歷去查找
192 #其他操作
193 print(l.count('v')) #統計某個元素在列表中出現的次數,沒有就返回0
194 print(l.index('s',1,5)) #從列表中找出某個值第一個匹配項的索引位置,可切片查找,沒有就返回0,沒有會報錯
195 #正向排序
196 l.sort()
197 print(l) # ['b', 'f', 'j', 's', 's', 't']
198 #反向排序
199 l.reverse()
200 print(l) #['t', 's', 's', 'j', 'f', 'b']
201
202
203 '''
204 6、字典dict:python中唯一的映射類型,鍵值對(key-value)儲存
205 特點:無序儲存、key必須是不可變類型(數字、字符串、元組)、哈希函數計算儲存地址
206 '''
207 #增
208 d = {}
209 d['s'] = [1,2,3] # dic[key] = value , key一定是不可變對象
210 print(d) #{'s': [1, 2, 3]}
211 d.setdefault('o') #在字典中添加鍵值對,如果只有鍵那對應的值是none
212 print(d) #{'s': [1, 2, 3], 'o': None}
213 d.setdefault(4,'s') #在字典中添加鍵值對
214 print(d) #{'s': [1, 2, 3], 'o': None, 4: 's'}
215 d.setdefault('o','ww')#如果原字典中存在設置的鍵值對,則他不會更改或者覆蓋
216 print(d) #{'s': [1, 2, 3], 'o': None, 4: 's'}
217
218 #刪
219 print(d.pop('age','沒有該數據')) # pop根據key刪除鍵值對,并返回對應的值,如果沒有key則返回默認返回值
220 print(d.popitem()) # 隨機刪除字典中的某個鍵值對,將刪除的鍵值對以元祖的形式返回 (4, 's')
221 del d['s'] # 沒有返回值。
222 print(d, d.clear()) #{} None
223
224 # 改
225 dic = {"name":"jin","age":18,"sex":"male", 'l':[1,2,3]}
226 dic2 = {"name":"alex","weight":75}
227 dic.update(dic2)# 將dic所有的鍵值對覆蓋添加(相同的覆蓋,沒有的添加)到dic2中
228 print(dic) #{'name': 'alex', 'age': 18, 'sex': 'male', 'weight': 75}
229 dic['name'] = 'sure'
230 dic['l'][1] = 'dfa'
231 print(dic) #{'name': 'sure', 'age': 18, 'sex': 'male', 'l': [1, 'dfa', 3], 'weight': 75}
232
233 # 查
234 v1 = dic['l'] #沒有會報錯
235 v2 = dic.get('s', '沒有該數據')
236 print(v1, v2) # [1, 'dfa', 3] 沒有該數據
237
238 # 其他操作
239 item = dic.items()
240 print(item, type(item))
241 #dict_items([('name', 'sure'), ('age', 18), ('sex', 'male'), ('l', [1, 'dfa', 3]), ('weight', 75)])
242 # <class 'dict_items'> 可迭代的類型
243 keys = dic.keys()
244 print(keys, type(keys))
245 #dict_keys(['name', 'age', 'sex', 'l', 'weight']) <class 'dict_keys'>
246 values = dic.values()
247 print(values, type(values))
248 #dict_values(['sure', 18, 'male', [1, 'dfa', 3], 75]) <class 'dict_values'>
249
250 # 字典的循環
251 print("=========遍歷key=========")
252 for key in dic:
253 print(key)
254 print("=========遍歷key-value=========")
255 for key in dic:
256 # print(key)
257 print(key, ":", dic[key])
258 print("=========遍歷key-value=========")
259 for key in dic.keys():
260 print(key, ":", dic[key])
261 print("=========遍歷key-value=========")
262 for key, value in dic.items():
263 print(key, ":", value)
264 print("=========遍歷key-value=========")
265 for item in dic.items():
266 print(item)
267
268
269 '''
270 7、元組tuple:只讀列表,可被查詢,使用切片
271 c = (1,2,3)
272 ''' 數據類型new
?
轉載于:https://www.cnblogs.com/sure-feng/p/9751685.html
總結
- 上一篇: 无线路由器的基础配置(一)
- 下一篇: VC驿站黑客编程(关机,重启,注销)