本節內容python
列表是咱們最之後最經常使用的數據類型之一,經過列表能夠對數據實現最方便的存儲、修改等操做git
names = ['Alex',"Tenglan",'Eric']
經過下標訪問列表中的元素,下標從0開始計數程序員
>>> names[0] 'Alex' >>> names[2] 'Eric' >>> names[-1] 'Eric' >>> names[-2] #還能夠倒着取 'Tenglan'
切片:取多個元素 shell
>>> names = ["Alex","Tenglan","Eric","Rain","Tom","Amy"] >>> names[1:4] #取下標1至下標4之間的數字,包括1,不包括4 ['Tenglan', 'Eric', 'Rain'] >>> names[1:-1] #取下標1至-1的值,不包括-1 ['Tenglan', 'Eric', 'Rain', 'Tom'] >>> names[0:3] ['Alex', 'Tenglan', 'Eric'] >>> names[:3] #若是是從頭開始取,0能夠忽略,跟上句效果同樣 ['Alex', 'Tenglan', 'Eric'] >>> names[3:] #若是想取最後一個,必須不能寫-1,只能這麼寫 ['Rain', 'Tom', 'Amy'] >>> names[3:-1] #這樣-1就不會被包含了 ['Rain', 'Tom'] >>> names[0::2] #後面的2是表明,每隔一個元素,就取一個 ['Alex', 'Eric', 'Tom'] >>> names[::2] #和上句效果同樣 ['Alex', 'Eric', 'Tom']
追加api
>>> names ['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy'] >>> names.append("我是新來的") >>> names ['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy', '我是新來的']
插入bash
>>> names ['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy', '我是新來的'] >>> names.insert(2,"強行從Eric前面插入") >>> names ['Alex', 'Tenglan', '強行從Eric前面插入', 'Eric', 'Rain', 'Tom', 'Amy', '我是新來的'] >>> names.insert(5,"從eric後面插入試試新姿式") >>> names ['Alex', 'Tenglan', '強行從Eric前面插入', 'Eric', 'Rain', '從eric後面插入試試新姿式', 'Tom', 'Amy', '我是新來的']
修改服務器
>>> names ['Alex', 'Tenglan', '強行從Eric前面插入', 'Eric', 'Rain', '從eric後面插入試試新姿式', 'Tom', 'Amy', '我是新來的'] >>> names[2] = "該換人了" >>> names ['Alex', 'Tenglan', '該換人了', 'Eric', 'Rain', '從eric後面插入試試新姿式', 'Tom', 'Amy', '我是新來的']
刪除網絡
>>> del names[2] >>> names ['Alex', 'Tenglan', 'Eric', 'Rain', '從eric後面插入試試新姿式', 'Tom', 'Amy', '我是新來的'] >>> del names[4] >>> names ['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy', '我是新來的'] >>> >>> names.remove("Eric") #刪除指定元素 >>> names ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy', '我是新來的'] >>> names.pop() #刪除列表最後一個值 '我是新來的' >>> names ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy']
擴展app
>>> names ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy'] >>> b = [1,2,3] >>> names.extend(b) >>> names ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy', 1, 2, 3]
拷貝frontend
l = ['1','2','3',[1,2,3]] re = l.copy() print(l) # ['1', '2', '3', [1, 2, 3]] print(re) # ['1', '2', '3', [1, 2, 3]] l[3].append(4) print(l) # ['1', '2', '3', [1, 2, 3, 4]] print(re) # ['1', '2', '3', [1, 2, 3, 4]] import copy ret = copy.copy(l) # 同上的結果,咱們稱爲淺拷貝 ret2 = copy.deepcopy(l) # 2份獨立的空看,咱們稱爲深拷貝 print(l) # ['1', '2', '3', [1, 2, 3, 4]] print(ret2) # ['1', '2', '3', [1, 2, 3, 4]] l[3].append(5) print(l) # ['1', '2', '3', [1, 2, 3, 4, 5]] print(ret2) # ['1', '2', '3', [1, 2, 3, 4]] # 淺拷貝是拷貝了一分內存指引,都指向一個地址,爲何這麼作,由於PYTHON爲了不數據類型裏面有無限大的子集,避免浪費
統計
>>> names ['Alex', 'Tenglan', 'Amy', 'Tom', 'Amy', 1, 2, 3] >>> names.count("Amy") 2
排序&翻轉
>>> names ['Alex', 'Tenglan', 'Amy', 'Tom', 'Amy', 1, 2, 3] >>> names.sort() #排序 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unorderable types: int() < str() #3.0裏不一樣數據類型不能放在一塊兒排序了,擦 >>> names[-3] = '1' >>> names[-2] = '2' >>> names[-1] = '3' >>> names ['Alex', 'Amy', 'Amy', 'Tenglan', 'Tom', '1', '2', '3'] >>> names.sort() >>> names ['1', '2', '3', 'Alex', 'Amy', 'Amy', 'Tenglan', 'Tom'] >>> names.reverse() #反轉 >>> names ['Tom', 'Tenglan', 'Amy', 'Amy', 'Alex', '3', '2', '1']
獲取下標
>>> names ['Tom', 'Tenglan', 'Amy', 'Amy', 'Alex', '3', '2', '1'] >>> names.index("Amy") 2 #只返回找到的第一個下標
元祖
元組其實跟列表差很少,也是存一組數,只不是它一旦建立,便不能再修改,因此又叫只讀列表
names = ("alex","jack","eric")
元組自己是不可變的,可是內部的元素能夠是可變類型
2個方法 一個 count 一個 index,能夠切片,索引取值,成員操做
請閉眼寫出如下程序。
程序:購物車程序
需求:
特性:不可修改
#!/usr/bin/env python #_*_coding:utf-8_*_ #strip 方法用於移除字符串頭尾指定的字符(默認爲空格)。 #str.strip([chars]); # chars移除字符串頭尾指定的字符。 這是一個包含的關係 name = "*joker**" print(name.strip("*")) print(name.lstrip("*")) #去除左邊 print(name.rstrip("*")) #去除右邊 #startswith,endswith name = "joker_li" print(name.endswith("li")) #是否以什麼結尾 print(name.startswith("joker")) #是否以什麼開頭 #replace name = "joker is good joker boy!" print(name.replace('joker','li')) #全部joker替換li print(name.replace('joker','li',1)) #從左到右替換1次 #find,rfind,index,rindex,count name = 'jokerk say hi' print(name.find('s')) #字符串也是能夠切片找不到則返回-1不會報錯,找到了則顯示索引 print(name.count('k')) #統計包含有多少個 #split name = 'root:x:0:0::/root/:bin/bash' print(name.split(':')) #默認分隔符爲空格 name = 'c:/a/b/c/d.txt' #想拿到頂級目錄 print(name.split('/',1)) #按多少次切片,從左邊 name = 'a|b|c' print(name.rsplit('|',1)) #按多少次切片,從右邊 #join tag = ' ' print(tag.join(['joker','li','good','boy'])) #可迭代對象必須都是字符串 #也就是說這個方法是將列表轉換爲字符串,若是tag有變量的話,就會循環加 #center,ljust,rjust,zfill name = 'joker' print(name.center(10,'_')) #不夠10個字符,用_補齊 print(name.ljust(10,'*')) #左對齊 print(name.rjust(10,'*')) #右對齊,注意這個引號內只能是一個字符 print(name.zfill(10)) #右對齊,用0補齊就是 #expandtabs name = 'joker\thello' print(name) print(name.expandtabs(4)) #expand擴張的意思,就是將tab建轉爲多少個空格 #lower,upper name = 'joker' print(name.lower()) #大寫變小寫,若是原本就是小寫,那就沒變化 print(name.upper()) #小寫變大寫,若是原本就是大寫,那就沒變化 #capitalize,swapcase,title name = 'joker li' print(name.capitalize()) #首字母大寫 print(name.swapcase()) #大小寫對調 print(name.title()) #每一個單詞的首字母大寫 #is數字系列 num1 = b'4' #bytes 類型 print(type(num1)) num2 = u'4' #unicode類型,在3裏默認就是這個類型 print(type(num2)) num3 = '四' #中文數字 num4 = 'Ⅳ' #羅馬數字 #isdigt,bytes,unicode print(num1.isdigit()) #是否是一個整數數字,若是是浮點數就會False print(num2.isdigit()) print(num3.isdigit()) #False print(num4.isdigit()) #羅馬數字 False ,不是一個整數 #isdecimal,uncicode #bytes類型無isdecimal方法 print(num2.isdecimal()) #檢查字符串是否只包含十進制字符。這種方法只存在於unicode對象 #注意:定義一個十進制字符串,只須要在字符串前添加 'u' 前綴便可 print(num3.isdecimal()) print(num4.isdecimal()) #isnumberic:unicode,中文數字,羅馬數字 #bytes類型無isnumberic方法 print(num2.isnumeric()) #判斷是否是數字,包括中文大寫數字,羅馬數字等 print(num3.isnumeric()) print(num4.isnumeric()) #三者不能判斷浮點數 num5='4.3' #全是false print(num5.isdigit()) print(num5.isdecimal()) print(num5.isnumeric()) # 最經常使用的是isdigit,能夠判斷bytes和unicode類型,這也是最多見的數字應用場景 # 若是要判斷中文數字或羅馬數字,則須要用到isnumeric #is print('===>') name='joker123' print(name.isalnum()) #字符串由字母和數字組成 print(name.isalpha()) #字符串只由字母組成 print(name.isidentifier()) #判斷是否是一個合法的表示符 print(name.islower()) #判斷是否是小寫 print(name.isupper()) #是否是大寫 print(name.isspace()) #判斷是否是空格 print(name.istitle()) #每一個單詞字母首字母大小
字典一種key - value 的數據類型,使用就像咱們上學用的字典,經過筆劃、字母來查對應頁的詳細內容
語法
info = { 'stu1101': "TengLan Wu", 'stu1102': "LongZe Luola", 'stu1103': "XiaoZe Maliya", }
字典的特性:
增長
>>> info["stu1104"] = "蒼井空" >>> info {'stu1102': 'LongZe Luola', 'stu1104': '蒼井空', 'stu1103': 'XiaoZe Maliya', 'stu1101': 'TengLan Wu'}
修改
>>> info['stu1101'] = "武藤蘭" >>> info {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1101': '武藤蘭'}
刪除
>>> info {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1101': '武藤蘭'} >>> info.pop("stu1101") #標準刪除姿式 '武藤蘭' >>> info {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'} >>> del info['stu1103'] #換個姿式刪除 >>> info {'stu1102': 'LongZe Luola'} >>> >>> >>> >>> info = {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'} >>> info {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'} #隨機刪除 >>> info.popitem() ('stu1102', 'LongZe Luola') >>> info {'stu1103': 'XiaoZe Maliya'}
查找
>>> info = {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'} >>> >>> "stu1102" in info #標準用法 True >>> info.get("stu1102") #獲取 'LongZe Luola' >>> info["stu1102"] #同上,可是看下面 'LongZe Luola' >>> info["stu1105"] #若是一個key不存在,就報錯,get不會,不存在只返回None Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'stu1105'
多級字典嵌套及操做
av_catalog = { "歐美":{ "www.youporn.com": ["不少免費的,世界最大的","質量通常"], "www.pornhub.com": ["不少免費的,也很大","質量比yourporn高點"], "letmedothistoyou.com": ["可能是自拍,高質量圖片不少","資源很少,更新慢"], "x-art.com":["質量很高,真的很高","所有收費,屌比請繞過"] }, "日韓":{ "tokyo-hot":["質量怎樣不清楚,我的已經不喜歡日韓範了","據說是收費的"] }, "大陸":{ "1024":["所有免費,真好,好人一輩子平安","服務器在國外,慢"] } } av_catalog["大陸"]["1024"][1] += ",能夠用爬蟲爬下來" print(av_catalog["大陸"]["1024"]) #ouput ['所有免費,真好,好人一輩子平安', '服務器在國外,慢,能夠用爬蟲爬下來']
其餘操做
#values >>> info.values() dict_values(['LongZe Luola', 'XiaoZe Maliya']) #keys >>> info.keys() dict_keys(['stu1102', 'stu1103']) #setdefault #setdefault:key不存在則設置默認值,而且將默認值添加到values中 #key存在則不設置默認,而且返回已經有的值 >>> info.setdefault("stu1106","Alex") 'Alex' >>> info {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'} >>> info.setdefault("stu1102","龍澤蘿拉") 'LongZe Luola' >>> info {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'} #update >>> info {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'} >>> b = {1:2,3:4, "stu1102":"龍澤蘿拉"} >>> info.update(b) >>> info {'stu1102': '龍澤蘿拉', 1: 2, 3: 4, 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'} #items info.items() dict_items([('stu1102', '龍澤蘿拉'), (1, 2), (3, 4), ('stu1103', 'XiaoZe Maliya'), ('stu1106', 'Alex')]) #經過一個列表生成默認dict,有個沒辦法解釋的坑,少用吧這個 >>> dict.fromkeys([1,2,3],'testd') {1: 'testd', 2: 'testd', 3: 'testd'}
循環dict
#方法1 for key in info: print(key,info[key]) #方法2 for k,v in info.items(): #由於會先把dict轉成list,速度慢,數據裏大時莫用 print(k,v)
程序練習
程序: 三級菜單
要求:
menu = { '北京':{ '海淀':{ '五道口':{ 'soho':{}, '網易':{}, 'google':{} }, '中關村':{ '愛奇藝':{}, '汽車之家':{}, 'youku':{}, }, '上地':{ '百度':{}, }, }, '昌平':{ '沙河':{ '老男孩':{}, '北航':{}, }, '天通苑':{}, '回龍觀':{}, }, '朝陽':{}, '東城':{}, }, '上海':{ '閔行':{ "人民廣場":{ '炸雞店':{} } }, '閘北':{ '火車戰':{ '攜程':{} } }, '浦東':{}, }, '山東':{}, } exit_flag = False current_layer = menu layers = [menu] while not exit_flag: for k in current_layer: print(k) choice = input(">>:").strip() if choice == "b": current_layer = layers[-1] #print("change to laster", current_layer) layers.pop() elif choice not in current_layer:continue else: layers.append(current_layer) current_layer = current_layer[choice]
集合是一個無序的,不重複的數據組合,它的主要做用以下:
經常使用操做
# !/usr/bin/env python # _*_coding:utf-8_*_ # Author:Joker a = t | s # t 和 s的並集 b = t & s # t 和 s的交集 c = t – s # 求差集(項在t中,但不在s中) d = t ^ s # 對稱差集(項在t或s中,但不會同時出如今兩者中) # set 無序,不重複序列 # 建立 # se = {'123',345} # print(type(se)) # s = set() # 建立一個空集合 # # 對比,以前咱們把元祖轉換成列表的方法 # l = list((1,2,3)) # print(l) # [1, 2, 3] 實際裏面運行了for循環,也就是init方法 # # s1 = set(l) # print(s1) # {1, 2, 3} 集合還有一個機制就是,若是有相同的就會去除 # 功能 # s = set() # s.add(1) # s.add(1) # print(s) # {1} # s.clear() # print(s) # 清空 # 差集 s1 = {11,22,33} s2 = {22,33,44} # s3= s1.difference(s2) # s1中存在,s2中不存在 {11} # s1.difference_update(s2) 更新到s1裏面,不須要建立新的集合 # print(s3) # 對稱差集 # s3 = s1.symmetric_difference(s2) # 對稱差集 {11, 44} # s1.symmetric_difference_update(s2) 更新到s1裏面,不須要建立新的集合 # print(s3) # 刪除 # s1.discard(11) # print(s1) # {33, 22} 移除指定元素,不存在不報錯 # s1.remove(11) # print(s1) {33, 22} ,不存在報錯 # ret = s1.pop() 隨機的,有返回值 # print(ret) # 交集 # ret = s1.intersection(s2) # print(ret) {33, 22} # s1.intersection_update(s2) # ret = s1.isdisjoint(s2) # print(ret) # 沒有交集返回true,有交集返回true # s1.issubset() # 是不是子序列,包含的關係 # s1.issuperset() # 是不是父序列,被包含的關係 # 並集 # ret = s1.union(s2) # print(ret) {33, 22, 11, 44} 並集 # li = [1,2,3] # s1.update(li) # 接收一個可迭代的相比add,它能夠添加個序列,而且循環執行add # # print(s1) # {33, 2, 3, 1, 11, 22}
對文件操做流程
現有文件以下
Somehow, it seems the love I knew was always the most destructive kind 不知爲什麼,我經歷的愛情老是最具毀滅性的的那種 Yesterday when I was young 昨日當我年少輕狂 The taste of life was sweet 生命的滋味是甜的 As rain upon my tongue 就如舌尖上的雨露 I teased at life as if it were a foolish game 我戲弄生命 視其爲愚蠢的遊戲 The way the evening breeze 就如夜晚的微風 May tease the candle flame 逗弄蠟燭的火苗 The thousand dreams I dreamed 我曾千萬次夢見 The splendid things I planned 那些我計劃的絢麗藍圖 I always built to last on weak and shifting sand 但我老是將之建築在易逝的流沙上 I lived by night and shunned the naked light of day 我夜夜笙歌 逃避白晝赤裸的陽光 And only now I see how the time ran away 事到現在我纔看清歲月是如何匆匆流逝 Yesterday when I was young 昨日當我年少輕狂 So many lovely songs were waiting to be sung 有那麼多甜美的曲兒等我歌唱 So many wild pleasures lay in store for me 有那麼多肆意的快樂等我享受 And so much pain my eyes refused to see 還有那麼多痛苦 個人雙眼卻視而不見 I ran so fast that time and youth at last ran out 我飛快地奔走 最終時光與青春消逝殆盡 I never stopped to think what life was all about 我從未停下腳步去思考生命的意義 And every conversation that I can now recall 現在回想起的全部對話 Concerned itself with me and nothing else at all 除了和我相關的 什麼都記不得了 The game of love I played with arrogance and pride 我用自負和傲慢玩着愛情的遊戲 And every flame I lit too quickly, quickly died 全部我點燃的火焰都熄滅得太快 The friends I made all somehow seemed to slip away 全部我交的朋友彷佛都不知不覺地離開了 And only now I'm left alone to end the play, yeah 只剩我一我的在臺上來結束這場鬧劇 Oh, yesterday when I was young 噢 昨日當我年少輕狂 So many, many songs were waiting to be sung 有那麼那麼多甜美的曲兒等我歌唱 So many wild pleasures lay in store for me 有那麼多肆意的快樂等我享受 And so much pain my eyes refused to see 還有那麼多痛苦 個人雙眼卻視而不見 There are so many songs in me that won't be sung 我有太多歌曲永遠不會被唱起 I feel the bitter taste of tears upon my tongue 我嚐到了舌尖淚水的苦澀滋味 The time has come for me to pay for yesterday 終於到了付出代價的時間 爲了昨日 When I was young 當我年少輕狂
基本操做
f = open('lyrics') #打開文件 first_line = f.readline() print('first line:',first_line) #讀一行 print('我是分隔線'.center(50,'-')) data = f.read()# 讀取剩下的全部內容,文件大時不要用 print(data) #打印文件 f.close() #關閉文件
經常使用操做
# !/usr/bin/env python # _*_coding:utf-8_*_ # Author:Joker # 打開文件 # f = open('db','r',encoding="utf-8") # encoding="utf-8",就是python默認幫你二進制轉換成字符串 # f = open('db','w') # 先清空,後寫入 # f = open('db','x') # 文件存在報錯,不存在建立寫內容 # f = open('db','a') # 追加 # f = open('db','rb') # 不用python處理,我直接跟0101打交到 # data = f.read() # print(data,type(data)) # 銀盤存的二進制,給咱們顯示的是字符串,那是否是有一個二進制轉換成字符串的過程 # f.close() # f = open('db','ab') # 字節追加 # f.write(bytes("hello",encoding='utf-8')) # 將字符串轉爲字節,而且以utf-8寫入 # f.close() # + 做用 # f = open('db','r+',encoding="utf-8") # 由於指針問題,默認讀到了最後,若是你定義了讀幾個字符,那麼指針會在第幾個字符那裏,可是你要追加寫的話就是從最後追加 # read 將指針調到某個字符的位置,若是是rb打開就是字節的位置 # data = f.read(1) # 一個字符 # print(f.tell()) # 位置就是3,按字節來的 # print(data) # # seek 就是按照字節的位置,而且是覆蓋原來的字節位置,若是是中文的話,seek1就會給你劈開 �111111 亂碼了 # f.seek(1) # print(f.tell()) # 獲取當前指針的位置 # f.write('1111') # f.close() # a+ 不管你怎麼調指針的位置,都是最後結尾處加內容 # w+ 先清空,在寫 # 操做文件 # f = open('db','r+',encoding="utf-8") # f.read() # 無參數,讀所有,有b按字節,無b按字符 # print(f.tell()) # 獲取當前指針位置 字節 # f.seek() # 調轉到哪一個位置 字節 # f.write() # 寫數據,有b就是寫字節,無b就是字符 # f.close() # 關閉文件 # f.flush() # 強刷到硬盤,以前是存在緩衝區,等待close時候,纔會刷到硬盤 # f.fileno() # 文件描述符,用於後面的socker # f.readable() # 判斷是否可讀,跟模式有關 # f.seekable() # 判斷是否能夠移動指針 # f.writable() # 判斷是否可寫 # f.readline() # 讀取一行,這時候指針換行了 # f.readline() # 讀取一行 # f.truncate() # 截斷數據,將指針後面的清空 # for line in f: # for 循環文件對象,一行一行 # print(line)
with語句
爲了不打開文件後忘記關閉,能夠經過管理上下文,即:
with open('log','r') as f: ...
如此方式,當with代碼塊執行完畢時,內部會自動關閉並釋放文件資源
程序練習
程序1: 實現簡單的shell sed替換功能
程序2:修改haproxy配置文件
1、查 輸入:www.oldboy.org 獲取當前backend下的全部記錄 2、新建 輸入: arg = { 'bakend': 'www.oldboy.org', 'record':{ 'server': '100.1.7.9', 'weight': 20, 'maxconn': 30 } } 3、刪除 輸入: arg = { 'bakend': 'www.oldboy.org', 'record':{ 'server': '100.1.7.9', 'weight': 20, 'maxconn': 30 } } 需求
global log 127.0.0.1 local2 daemon maxconn 256 log 127.0.0.1 local2 info defaults log global mode http timeout connect 5000ms timeout client 50000ms timeout server 50000ms option dontlognull listen stats :8888 stats enable stats uri /admin stats auth admin:1234 frontend oldboy.org bind 0.0.0.0:80 option httplog option httpclose option forwardfor log global acl www hdr_reg(host) -i www.oldboy.org use_backend www.oldboy.org if www backend www.oldboy.org server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000 原配置文件
需知:
1.在python2默認編碼是ASCII, python3裏默認是unicode
2.unicode 分爲 utf-32(佔4個字節),utf-16(佔兩個字節),utf-8(佔1-4個字節), so utf-16就是如今最經常使用的unicode版本, 不過在文件裏存的仍是utf-8,由於utf8省空間
3.在py3中encode,在轉碼的同時還會把string 變成bytes類型,decode在解碼的同時還會把bytes變回string
1 以什麼編碼存的就要以什麼編碼取出
ps:內存固定使用unicode編碼,
咱們能夠控制的編碼是往硬盤存放或者基於網絡傳輸選擇編碼
2 數據是最早產生於內存中,是unicode格式,要想傳輸須要轉成bytes格式
#unicode----->encode(utf-8)------>bytes
拿到bytes,就能夠往文件內存放或者基於網絡傳輸
#bytes------>decode(gbk)------->unicode
3 python3中字符串被識別成unicode
python3中的字符串encode獲得bytes
4 瞭解
python2中的字符串就bytes
python2中在字符串前加u,就是unicode
第一階段
打開python解釋器,notepad++,pychar 加載到內存
第二階段
寫一個文件就是
內存-endoce-bytes(二進制)
顯示文件就是
硬盤-decode-unicode(萬國碼)
第三階段
執行階段,針對的是內部定義新的內存空間,例如變量
數據是最早產生於內存中,是unicode格式,要想傳輸須要轉成bytes格式
#unicode----->encode(utf-8)------>bytes
拿到bytes,就能夠往文件內存放或者基於網絡傳輸
#bytes------>decode(gbk)------->unicode
python解釋器在加載 .py 文件中的代碼時,會對內容進行編碼(默認ascill)
ASCII(American Standard Code for Information Interchange,美國標準信息交換代碼)是基於拉丁字母的一套電腦編碼系統,主要用於顯示現代英語和其餘西歐語言,其最多隻能用 8 位來表示(一個字節),即:2**8 = 256-1,因此,ASCII碼最多隻能表示 255 個符號。
關於中文
爲了處理漢字,程序員設計了用於簡體中文的GB2312和用於繁體中文的big5。
GB2312(1980年)一共收錄了7445個字符,包括6763個漢字和682個其它符號。漢字區的內碼範圍高字節從B0-F7,低字節從A1-FE,佔用的碼位是72*94=6768。其中有5個空位是D7FA-D7FE。
GB2312 支持的漢字太少。1995年的漢字擴展規範GBK1.0收錄了21886個符號,它分爲漢字區和圖形符號區。漢字區包括21003個字符。2000年的 GB18030是取代GBK1.0的正式國家標準。該標準收錄了27484個漢字,同時還收錄了藏文、蒙文、維吾爾文等主要的少數民族文字。如今的PC平臺必須支持GB18030,對嵌入式產品暫不做要求。因此手機、MP3通常只支持GB2312。
從ASCII、GB23十二、GBK 到GB18030,這些編碼方法是向下兼容的,即同一個字符在這些方案中老是有相同的編碼,後面的標準支持更多的字符。在這些編碼中,英文和中文能夠統一地處理。區分中文編碼的方法是高字節的最高位不爲0。按照程序員的稱呼,GB23十二、GBK到GB18030都屬於雙字節字符集 (DBCS)。
有的中文Windows的缺省內碼仍是GBK,能夠經過GB18030升級包升級到GB18030。不過GB18030相對GBK增長的字符,普通人是很難用到的,一般咱們仍是用GBK指代中文Windows內碼。
顯然ASCII碼沒法將世界上的各類文字和符號所有表示,因此,就須要新出一種能夠表明全部字符和符號的編碼,即:Unicode
Unicode(統一碼、萬國碼、單一碼)是一種在計算機上使用的字符編碼。Unicode 是爲了解決傳統的字符編碼方案的侷限而產生的,它爲每種語言中的每一個字符設定了統一而且惟一的二進制編碼,規定雖有的字符和符號最少由 16 位來表示(2個字節),即:2 **16 = 65536,
注:此處說的的是最少2個字節,可能更多
UTF-8,是對Unicode編碼的壓縮和優化,他再也不使用最少使用2個字節,而是將全部的字符和符號進行分類:ascii碼中的內容用1個字節保存、歐洲的字符用2個字節保存,東亞的字符用3個字節保存...
因此,python解釋器在加載 .py 文件中的代碼時,會對內容進行編碼(默認ascill)
#!/usr/bin/env python #_*_coding:utf-8_*_ #三元運算 #if條件成立的結果 if 條件 else else條件成立的結果 #原來邏輯 # a,b=10,20 # if a > b: # c = 5 # else: # c = 10 # print(c) #三元邏輯 # a,b=10,20 # c = 5 if a>b else 10 # print(c) #隊列:先進先出 # queue_l=[] #入隊 # queue_l.append('first') # queue_l.append('second') # queue_l.append('third') # print(queue_l) #出隊 # print(queue_l.pop(0)) # print(queue_l.pop(0)) # print(queue_l.pop(0)) #堆棧:先進後出,後進先出 # l=[] # #入棧 # l.append('first') # l.append('second') # l.append('third') # #出棧 # print(l) # print(l.pop()) # print(l.pop()) # print(l.pop()) #列表,集合 # list = [i for i in range(10)] #列表推倒式 # print(list) # set = {i for i in range(10)} #集合推倒式 # print(set) # tuple = i for i in range(10) #元祖不行 # print(tuple) # str = i for i in 'abc' #字符串不行 #in:not in #字符串:子字符串 #列表:元素 #元組:元素 #字典:key # d={'a':1,'b':2,'c':3} # print('b' in d) #解壓法 # a,b,*_=[1,2,3,4,5] # print(a,b) # a,b,c,*_={1,2,3,4,5} # print(a,b,c) # a,b,c,d,*_=(1,2,3,4,5) # print(a,b,c,d) # a,b,c,*_='abcd' # print(a,b,c) # a,b,c,*_={1:'a',2:"b",3:'c'} # print(a,b,c) #enumerate 列表,字典,元祖,字典,字符串,集合 # 對於一個可迭代的(iterable)/可遍歷的對象(如列表、字符串),enumerate將其組成一個索引序列,利用它能夠同時得到索引和值 # 必須i v取值,由於單獨I 的話是一個元祖輸出 # (0, 'a') # (1, 'b') # (2, 'c') # dict = { # 1:'a', # 2:'b', # 3:'c' # } # for i,v in enumerate(dict,1): # print(i,dict[v]) # # for i,v in enumerate(dict): # print(i+1,dict[v]) # # list = [1,2,3,4] # for i,v in enumerate(list,1): # print(i,list[i-1]) # str = 'abc' # for i,v in enumerate(str,0): # print(i,v) # set = {1,2,3,4} # for i,v in enumerate(set,0): #集合原本無序,可是enumerate將其轉化爲index,values的元祖 # print(i,v) # tuple = (1,2,3,4) # for i,v in enumerate(tuple,0): # print(i,v) #數據類型的轉換 # str = 'hello' # print(str) # print(list(str)) # print(tuple(str)) # print(set(str)) # list = [1,2,3] # print(list) # print(str(list)) # print(tuple(list)) # print(set(list)) # tuple = (1,2,3) # print(tuple) # print(str(tuple)) # print(list(tuple)) # print(set(tuple)) # set = {1,2,3} # print(set) # print(str(set)) # print(list(set)) # print(tuple(set)) # info=dict([('name','egon'),('age',18)]) # print(info) # print(str(info)) # print(tuple(info)) # print(set(info)) # print(list(info)) #字典生成 # info=dict([('name','egon'),('age',18)]) # print(info) # info=dict(name='egon',age=18,sex='male') # print(info)