Python入門篇(四)之字串、字典、集合

來源:互聯網
上載者:User

標籤:Python   字典   

1、字串操作

字串是無法修改的,只能作為查詢.
在python中,加了引號的字元就是字串類型,python並沒有字元類型。
定義:name=‘kim‘ #name=str(‘kim‘)
用於標識:描述性的內容,如姓名,性別,國籍,種族
那單引號、雙引號、多引號有什麼區別呢? 讓我大聲告訴你,單雙引號木有任何區別,只有下面這種情況 你需要考慮單雙的配合
msg = "My name is Kim , I‘m 18 years old!"

多引號什麼作用呢?作用就是多行字串必須用多引號
msg = ‘‘‘<br/>今天我想寫首小詩,<br/>歌頌我的同桌,<br/>你看他那烏黑的短髮,<br/>好像一隻炸毛雞。<br/>‘‘‘ <br/>print(msg)

#!/usr/bin/python# _*_ coding:utf-8 _*_# Aothr: Kimname = ‘my name is {name} and i am {years} old‘print(name.capitalize()) #首字母大寫  ==>執行結果:My name is {name} and i am {years} oldprint(name.count("a")) #統計字母a的個數=>執行結果:5print(name.center(50,"-")) #統計50個字元,不夠以-湊足,美觀列印=>執行結果:------my name is {name} and i am {years} old------print(name.endswith("x")) #判斷字串是否以什麼結尾,比如判斷郵件地址是否以.com結尾,返回布爾值=>執行結果:Falseprint(name.expandtabs(tabsize=30)) #tab鍵轉換成多少個空格=>執行結果:print(name.find("name")) #尋找字元返回的是索引,name在my name....(m-->0,y-->1......)=>執行結果:3print(name[name.find("y"):]) #字串切片,列印y到最後=>執行結果:y name is {name} and i am {years} oldprint(name.format(name=‘alex‘,years=‘23‘)) #格式=>執行結果:my name is alex and i am 23 oldprint(name.format_map( {‘name‘:‘alex‘,‘years‘:12} )) #嵌入字典=>執行結果:my name is alex and i am 23 oldprint(name.index("and")) #取索引=>執行結果:18print(‘ab123‘.isalnum()) #判斷是否是阿拉伯數字=>執行結果:Trueprint(‘abA‘.isalpha())=>執行結果:Trueprint(‘1.22‘.isdecimal()) #判斷十進位=>執行結果:Falseprint(‘1A‘.isdigit()) #判斷是否數字=>執行結果:Falseprint(‘222‘.isidentifier()) #判斷是不是一個合法的標識符,或者是否是一個合法的變數=>執行結果:Falseprint(‘a‘.islower()) #判斷是否小寫=>執行結果:Trueprint(‘2AAA‘.isupper() #判斷是否大寫=>執行結果:Falseprint(‘+‘.join( [‘1‘,‘2‘,‘3‘]) )=>執行結果:1+2+3print( name.ljust(50,‘*‘) ) #統計50個字元,不夠用*在右側湊足=>執行結果:my name is {name} and i am {years} old************print( name.rjust(50,‘-‘) ) #統計50個字元,不夠用-在左側湊足=>執行結果:------------my name is {name} and i am {years} oldprint(‘Alex‘.lower()) #大寫變小寫=>執行結果:alexprint(‘Alex‘.upper()) #小寫變大寫=>執行結果:ALEXprint(‘\nAlex‘.lstrip()) #去掉左邊分行符號=>執行結果:Alexprint(‘Alex\n‘.rstrip()) #去掉右邊分行符號=>執行結果:Alexprint(‘     Alex\n‘.strip()) #去掉換行和空格符=>執行結果:Alexp = str.maketrans("abcdef","123456") #類似加密,需要對齊(a-->1,b-->2,c-->3,以此類推)print("alex li".translate(p))  =>執行結果:1l5x liprint(‘alex li‘.replace(‘l‘,‘L‘,1)) #替換=>執行結果:aLex liprint(‘alex li‘.rfind(‘l‘)) #找到最右邊的值,返回下標=>執行結果:5print(‘al ex lil‘.split(‘l‘)) #以l作為分隔字元=>執行結果:[‘a‘, ‘ ex ‘, ‘i‘, ‘‘]print(‘1+2+3+4‘.split(‘\n‘)) #以分行符號分隔=>執行結果:[‘1+2+3+4‘]print(‘1+2\n+3+4‘.splitlines()) #識別分行符號分隔=>執行結果:[‘1+2‘, ‘+3+4‘]print(‘Alex Li‘.swapcase()) #大寫變小寫,小寫變大寫=>執行結果:aLEX lIprint(‘alex li‘.title()) #變成主題=>執行結果:Alex Liprint(‘alex li‘.zfill(50)) #沒啥卵用=>執行結果:0000000000000000000000000000000000000000000alex li
2、字典操作

字典是一種key-value的資料類型,使用就想我們上學使用的字典,通過筆畫、字母來差對應頁的詳細內容。字典可以嵌套列表
在{}內用逗號分隔,可以存放多個key:value的值,value可以是任意類型
定義:
info={‘name‘:‘egon‘,‘age‘:18,‘sex‘:18}
info=dict({‘name‘:‘egon‘,‘age‘:18,‘sex‘:18})
用於標識:儲存多個值的情況,每個值都有唯一一個對應的key,可以更為方便高效地取值

2.1、文法:
info = {    ‘stu1101‘:"Zhang san"    ‘stu1102‘:"Li si"    ‘stu1103‘:"Wang wu"}print(info)print(info["stu1101"]) #取值執行結果:{‘stu1102‘: ‘Li si‘, ‘stu1103‘: ‘Wang wu‘, ‘stu1101‘: ‘Zhang san‘}Zhang san
2.2、字典的特性:

(1)dict是無序的,因為字典沒有下標,也不需要下標。
(2)key必須是唯一的,so,天生去重

字典如下:info = {    ‘stu1101‘:"Zhang san"    ‘stu1102‘:"Li si"    ‘stu1103‘:"Wang wu"}
2.3、字典的操作(1)增加
info[‘stu1104‘] = "KIM"print(info)執行結果:{‘stu1101‘: ‘Zhang san‘, ‘stu1104‘: ‘KIM‘, ‘stu1103‘: ‘Wang wu‘, ‘stu1102‘: ‘Li si‘}
(2)修改
info[‘stu1101‘] = "Grace"print(info)執行結果:{‘stu1102‘: ‘Li si‘, ‘stu1103‘: ‘Wang wu‘, ‘stu1104‘: ‘KIM‘, ‘stu1101‘: ‘Grace‘}
(3)刪除
del info["stu1101"]info.pop("stu1101") #標準刪除姿勢info.popitem() #隨機刪除print(info)執行結果:{‘stu1103‘: ‘Wang wu‘, ‘stu1102‘: ‘Li si‘}
(4)尋找
print("stu1102" in info) #尋找stu1102是否在info字典中執行結果:Trueprint(info.get("stu1101")) #擷取print(info["stu1101"]) #和get方法是一樣的,但是如果key不存在,就會報錯,get不會,不存在只會返回none執行結果:Zhang sanZhang sanprint(info.get(‘stu1106‘))執行結果:Noneprint(info["stu1106"])執行結果:KeyError: ‘stu1106‘
(5)多級字典嵌套及操作
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‘: [‘全部免費,真好,好人一生平安‘, ‘北京歡迎你‘]}, ‘歐美‘: {‘letmedothistoyou.com‘: [‘多是自拍,高品質圖片很多‘, ‘資源不多,更新慢‘], ‘x-art.com‘: [‘品質很高,真的很高‘, ‘全部收費,屌比請繞過‘], ‘www.pornhub.com‘: [‘很多免費的,也很大‘, ‘品質比yourporn高點‘], ‘www.youporn.com‘: [‘很多免費的,世界最大的‘, ‘品質一般‘]}, ‘日韓‘: {‘tokyo-hot‘: [‘品質怎樣不清楚,個人已經不喜歡日韓範了‘, ‘聽說是收費的‘]}}av_catalog["大陸"]["1024"][1] += ",可以使用爬蟲" #增加內容print(av_catalog["大陸"]["1024"]) #只列印大陸--1024內容執行結果:[‘全部免費,真好,好人一生平安‘, ‘北京歡迎你,可以使用爬蟲‘]
(6)其他動作
info = {    ‘stu1101‘:"Zhang san",    ‘stu1102‘:"Li si",    ‘stu1103‘:"Wang wu",}(1)valuesprint(info.values()) #列印所有的value執行結果:dict_values([‘Li si‘, ‘Zhang san‘, ‘Wang wu‘])(2)keysprint(info.keys()) #列印所有的key執行結果:dict_keys([‘stu1103‘, ‘stu1102‘, ‘stu1101‘])(3)setdefault 在字典中取值,如果能取到直接返回,如果無法取到值,則會進行建立增加。info.setdefault("stu1106","Alex") #增加索引值對print(info)執行結果:{‘stu1102‘: ‘Li si‘, ‘stu1103‘: ‘Wang wu‘, ‘stu1106‘: ‘Alex‘, ‘stu1101‘: ‘Zhang san‘}info.setdefault("stu1102","Alex")print(info)執行結果:{‘stu1101‘: ‘Zhang san‘, ‘stu1102‘: ‘Li si‘, ‘stu1103‘: ‘Wang wu‘}(4)updateinfo = {    ‘stu1101‘:"Zhang san",    ‘stu1102‘:"Li si",    ‘stu1103‘:"Wang wu",}b = {    "stu1104":"xiaoqiang",    1:2,    3:4}info.update(b) #將b字典合并到info字典中print(info)執行結果:{‘stu1103‘: ‘Wang wu‘, 3: 4, ‘stu1102‘: ‘Li si‘, 1: 2, ‘stu1101‘: ‘Zhang san‘, ‘stu1104‘: ‘xiaoqiang‘}(5)itemsprint(info.items()) #列印出索引值對執行結果:dict_items([(‘stu1102‘, ‘Li si‘), (‘stu1101‘, ‘Zhang san‘), (‘stu1103‘, ‘Wang wu‘)])
(7)迴圈字典dict
方法一:info = {    ‘stu1101‘:"Zhang san",    ‘stu1102‘:"Li si",    ‘stu1103‘:"Wang wu",}for i in info:    print(i,info[i])執行結果:stu1101 Zhang sanstu1102 Li sistu1103 Wang wu方法二:for k,v in info.items(): #會先把dict轉成list,資料裡大時莫用    print(k,v)執行結果:stu1102 Li sistu1103 Wang wustu1101 Zhang san    
2.4、程式練習

程式: 三級菜單

要求:

1.列印省、市、縣三級菜單
2.可返回上一級
3.可隨時退出程式
很low的程式,只是練習而已,別當真~!

#!/usr/bin/python# _*_ coding:utf-8 _*_# Aothr: Kiminfo = {    "廣東省":{        "中山市":{            "東區":["威尼斯","行政中心"],            "南區":["樹木園","中澳花園"],            "西區":["汽車站","劍橋郡"]},        "廣州市":{            "天河區":["珠江新城","天河客運站"],            "花都區":["培正學院","廣州北站"],        }    },    "福建省":{        "廈門市":{            "廈門":["鼓浪嶼","廈門大學"]}    },    "湖南省":{        "長沙市":{            "長沙":["臭豆腐專賣店","鳳凰古城"],}    }}exit_flag = False #增加標誌位while True:    for i in info:        print(i)    province = input("請輸入你想要去的省份:")    if province in info:            while True:                for i2 in info[province]:                    print("\t", i2)                city = input("如需返回請上級菜單請輸入b,退出請按q,請選擇地市:")                if city in info[province]:                    while True:                        for i3 in info[province][city]:                            print("\t\t", i3)                        area = input("如需返回請上級菜單請輸入b,退出請按q,請選擇地區:")                        if area in info[province][city]:                            while True:                                for i4 in info[province][city][area]:                                    print(i4)                                site = input("如需返回上級菜單請按b,退出請按q,請選擇地點:")                                if site in info[province][city][area]:                                    print("正在為你選擇合適路線......\n導航開始")                                    back = input("最後一級菜單,可按b返回上一級菜單,退出請按q:")                                    if back == "b":                                        pass                                    elif back == "q":                                        exit()                                elif site == ‘q‘:                                    exit()                                elif site == ‘b‘:                                    break                                else:                                    print("你的輸入錯誤,請重新輸入:")                        elif area == ‘q‘:                            exit()                        elif area == ‘b‘:                            break                        else:                            print("你的輸入錯誤,請重新輸入:")                elif city == ‘q‘:                    exit()                elif city == ‘b‘:                    break                else:                    print("你的輸入錯誤,請重新輸入:")    elif province == ‘q‘:        exit()    else:        print("你的輸入錯誤,請重新輸入:")

購物車程式最佳化:
使用者入口:
1、商品資訊存在檔案裡
2、已購商品,餘額記錄
使用者入口:
1、可以添加商品,修改商品價格

3、集合操作

集合是一個無序的,不重複的資料群組合,它的主要作用如下:
去重,把一個列表變成集合,就自動去重了
關係測試,測試兩組資料之前的交集、差集、並集等關係

3.1、集合去重功能
list_1 = [1,4,5,7,3,6,7,9] -->列表中有重複的值list_1 = set(list_1)-->設定成集合print(list_1,type(list_1)) -->去除了重複的7執行結果:{1, 3, 4, 5, 6, 7, 9} <class ‘set‘>
3.2、關係測試
list_1 = [1,4,5,7,3,6,7,9]list_1 = set(list_1)list_2 =set([2,6,0,66,22,8,4])#交集print(list_1.intersection(list_2))print(list_1 & list_2) -->符號標記法,使用“&”符號執行結果:{4, 6}#並集print(list_1.union(list_2))print(list_1 | list_2) -->符號標記法,使用“|”符號執行結果:{0, 1, 2, 3, 4, 5, 6, 7, 66, 9, 8, 22}#差集,in list_1 but not in list_2print(list_1.difference(list_2))print(list_2.difference(list_1))print(list_1 - list_2) -->符號標記法,使用“-”符號print(list_2 - list_1) 執行結果:{1, 3, 5, 9, 7}{0, 8, 2, 66, 22}#子集和父集list_3=set([1,3,7])print(list_3.issubset(list_1)) -->判斷list_3是否為list_1的子集print(list_1.issuperset(list_2)) -->判斷list_1是否為list_2的父集執行結果:True False#對稱差集list_1 = set([1,4,5,7,3,6,7,9])list_2 =set([2,6,0,66,22,8,4])print(list_1.symmetric_difference(list_2)) -->相當於去重後的並集print(list_1 ^ list_2) -->符號標記法,使用“^”符號執行結果:{0, 1, 2, 66, 3, 5, 7, 8, 9, 22}#判斷集合是否有交集list_3=set([1,3,7])list_4 = set([5,6,8,7])print(list_3.isdisjoint(list_4))執行結果:True
3.3、基本操作(1)添加一項
list_1 = set([1,4,5,7,3,6,7,9])print(list_1.add(999))執行結果:{1, 3, 4, 5, 6, 7, 999, 9}
(2)添加多項
print(list_1.update([888,777,555]))執行結果:{1, 3, 4, 5, 6, 7, 9, 777, 555, 888}
(3)刪除項,remove刪除不存在的項時會報錯,使用discard不會報錯
list_1.remove(888) --->方法一list_1.discard(888) --->方法二print(list_1)執行結果:{1, 3, 4, 5, 6, 7, 9, 777, 555}list_1.remove(89999)執行結果:KeyError: 89999
(4)隨機刪除
list_1 = set([{1, 3, 4, 5, 6, 7, 9, 777, 555, 888}])print(list_1.pop()) #隨機刪除print(list_1.pop())print(list_1.pop())執行結果:134
(5)set的長度
list_1 = set([{1, 3, 4, 5, 6, 7, 9, 777, 555, 888}])print(len(list_1))執行結果:10
(6)判斷x是否是s的成員
list_1 = set([{1, 3, 4, 5, 6, 7, 9, 777, 555, 888}])print(666 in list_1) print(666 not in list_1)執行結果:FalseTrue
(7)複製
list_1 = set([{1, 3, 4, 5, 6, 7, 9, 777, 555, 888}])list_9 = list_1.copy()print(list_9)執行結果:{1, 3, 4, 5, 6, 7, 9, 777, 555, 888}

參考連結:金角大王

Python入門篇(四)之字串、字典、集合

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.