Python Introductory chapter (iv) string, dictionary, collection

Source: Internet
Author: User

1. String manipulation

The string cannot be modified, only as a query.
In Python, the quoted character is the string type, and Python does not have a character type.
Definition: name= ' Kim ' #name =str (' Kim ')
Used to identify: descriptive content, such as name, gender, nationality, ethnicity
What's the difference between single quotes, double quotes, and multiple quotes? Let me tell you aloud that there is no difference between single and double quotes, only the following situation you need to consider a single pair of mates
msg = "My name is Kim , I‘m 18 years old!"

What does a multi-quote function do? The function is that multiple lines of string must be in multiple quotes
msg = ‘‘‘<br/>今天我想写首小诗,<br/>歌颂我的同桌,<br/>你看他那乌黑的短发,<br/>好像一只炸毛鸡。<br/>‘‘‘ <br/>print(msg)

#!/usr/bin/python# _*_ coding:utf-8 _*_# aothr:kimname = ' My name ' {name} and I am {years} old ' Print (Name.capitalize ()) #首字母大写 ==> Execution Result: My name is {name} and I am {years} oldprint (Name.count ("a")) #统计字母a的个数 "=" Result: 5print (Name.center (50), "-")) #统计50个字符, not enough to-fill, beautiful print + results:------My name is {name} and I am {years} old------print (Name.endswith ("X")) # Determines whether the string ends with, for example, whether the e-mail address ends in. com, returns a Boolean value of ~ = Execution Result: Falseprint (Name.expandtabs (tabsize=30)) #tab键转换成多少个空格 Execution Result: print (Name.find ("name")) #查找字符返回的是索引, name in my name .... (M-->0,y-->1 ...) = = Execution Result: 3print (Name[name.find ("Y"):]) #字符串切片, print y to last = = Execute Result: Y name is {name} and I am {years} oldprint (Name.format (  Name= ' Alex ', Years= ')) #格式 + = execution Result: My name is Alex and I am at Oldprint (name.format_map ({' name ': ' Alex ', ' Years ': 12})) #嵌入字典 = = The result of the execution: My name is Alex and I Am Oldprint (Name.index ("and")) #取索引 = + Execution Result: 18print (' ab123 '. Isalnum ()) #判断是否是阿拉 Job number = results: Trueprint (' AbA '. Isalpha ()) + execution Result: Trueprint (' 1.22 '. Isdecimal ()) #判断十进制 = = Execution Result: FAlseprint (' 1 a '. IsDigit ()) #判断是否数字 + = Execution Result: Falseprint (' 222 '. Isidentifier ()) #判断是不是一个合法的标识符, or whether it is a valid variable = Execution Result: Falseprint (' a '. Islower ()) #判断是否小写 = = Execution Result: Trueprint (' 2AAA '. Isupper () #判断是否大写 = = Execution Result: Falseprint (' + '. Join ( [' 1 ', ' 2 ', ' 3 ']) ) = Results of execution: 1+2+3print (Name.ljust ()) #统计50个字符, not enough * on the right side to fill up the result: My name is {name} and I am {years} old*********** *print (Name.rjust (), '-') #统计50个字符, not enough--on the left to fill out the results:------------My name is {name} and I am {years} oldprint (' Alex '. L Ower ()) #大写变小写 The results of the execution: Alexprint (' Alex ' Upper ()) #小写变大写 = + Execution Result: Alexprint (' \nalex '. Lstrip ()) #去掉左边换行符 Execution Result: Alexprint (' alex\n '. Rstrip ()) #去掉右边换行符 + = Execution Result: Alexprint (' alex\n '. Strip ()) #去掉换行和空格符 = = Execution Result: Alexp = Str.maketrans ("abcdef", "123456") #类似加密, need to align (a-->1,b-->2,c-->3, and so on) print ("Alex Li". Translate (p)) = Execution Result: 1l5x liprint (' Alex Li '. replace (' l ', ' l ', 1)) #替换 + = Execution Result: Alex Liprint (' Alex Li ' RFind (' l ')) #找到最右边的值, return subscript = Execution Result: 5print (' Al ex Lil '. Split (' L ')) #以l作为分隔符 + = execution Result: [' a ', ' ex ', ' I ', ']Print (' 1+2+3+4 '. Split (' \ n ')) #以换行符分隔 = = Execution Result: [' 1+2+3+4 ']print (' 1+2\n+3+4 '. Splitlines ()) #识别换行符分隔 = = Execution Result: [' 1+2 ', ' +3+4 ']print (' Alex Li '. swapcase ()) #大写变小写, lowercase to uppercase = + Execution Result: Alex Liprint (' Alex Li '. Title ()) #变成主题 = = Results of the execution: Alex Liprint (' Alex Li '. Zfill ()) #没啥卵用 and results: 0000000000000000000000000000000000000000000alex Li
2. Dictionary operation

The dictionary is a kind of key-value data type, using the dictionary that we use to go to school, the detail content of the corresponding page by stroke, letter. Dictionaries can have nested lists
Separated by commas within {}, can hold multiple key:value values, value can be any type
Defined:
info={' name ': ' Egon ', ' age ': +, ' sex ': 18}
Info=dict ({' name ': ' Egon ', ' age ': +, ' sex ': 18})
Used to identify: store multiple values, each value has a unique key, can be more convenient and efficient to take the value

2.1. Syntax:
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, the characteristics of the dictionary:

(1) Dict is unordered, because the dictionary does not subscript, and does not need subscript.
(2) key must be unique, so, naturally go heavy

字典如下:info = {    ‘stu1101‘:"Zhang san"    ‘stu1102‘:"Li si"    ‘stu1103‘:"Wang wu"}
2.3, the operation of the dictionary (1) increased
info[‘stu1104‘] = "KIM"print(info)执行结果:{‘stu1101‘: ‘Zhang san‘, ‘stu1104‘: ‘KIM‘, ‘stu1103‘: ‘Wang wu‘, ‘stu1102‘: ‘Li si‘}
(2) Modification
info[‘stu1101‘] = "Grace"print(info)执行结果:{‘stu1102‘: ‘Li si‘, ‘stu1103‘: ‘Wang wu‘, ‘stu1104‘: ‘KIM‘, ‘stu1101‘: ‘Grace‘}
(3) Delete
del info["stu1101"]info.pop("stu1101") #标准删除姿势info.popitem() #随机删除print(info)执行结果:{‘stu1103‘: ‘Wang wu‘, ‘stu1102‘: ‘Li si‘}
(4) Find
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) Multi-level dictionary nesting and operation
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) Other operations
  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 the value in the dictionary, if it can be returned directly, if the value cannot be taken, the creation will increase. Info.setdefault ("stu1106", "Alex") #增加键值对print (info) execution result: {' stu1102 ': ' Li si ', ' stu1103 ': ' Wang wu ', ' stu1106 ': ' Alex ', ' Stu1101 ': ' Zhang San '}info.setdefault ("stu1102", "Alex") print (info) execution result: {' stu1101 ': ' Zhang San ', ' stu1102 ': ' Li si ', ' stu1103 ': ' Wang Wu ' (4) Updateinfo = {' stu1101 ': "Zhang san", ' stu1102 ': "Li si", ' stu1103 ': "Wang Wu",}b = {"St u1104 ":" Xiaoqiang ", 1:2, 3:4}info.update (b) #将b字典合并到info字典中print (info) execution result: {' stu1103 ': ' Wang Wu ', 3:4, ' stu1102 ': ' Li si ', 1:2, ' stu1101 ': ' Zhang san ', ' stu1104 ': ' Xiaoqiang '} (5) Itemsprint (Info.items ())) #打印出键值对执行结果:d ict_items ([(' stu1102 ', ' Li si '), (' stu1101 ', ' Zhang san '), (' stu1103 ', ' Wang Wu ')])  
(7) Circular Dictionary 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. Procedure Practice

Program: Level Three Menu

Requirements:

1. Print provincial, city, and county level three menus
2. Return to the upper level
3. Can exit the program at any time
Very low program, just practice, don't take it seriously!

#!/usr/bin/python# _*_ coding:utf-8 _*_# aothr:kiminfo = {"Guangdong province": {"Zhongshan": {"Eastern": ["Venice", "Administrative center"], "Southern Area": ["Arboretum", "Sino-Australian Garden"], "West Side": ["Bus Stop", "Cambridge County"]}, "Guangzhou": {"Tianhe District": ["Zhujiang New Town", "Tianhe Bus Terminal"], " Huadou District ": [" Pei Zheng College "," Guangzhou North Station "],}," Fujian province ": {" Xiamen ": {" Amoy ": [" Gulangyu "," University of Xiamen "]}," Hunan province ": {" Changsha City ": {" Changsha ": [" Stinky Tofu Store "," Phoenix City "],}}}exit_flag = False #增加标志位while true:for i in Info:print (i) pro                    Vince = input ("Please enter the province you want to go to:") if Province in Info:while true:for I2 in info[province]: Print ("\ T", i2) City = input ("If you want to return to the parent menu Please enter B, exit please press Q, please select the municipality:") If the cities in Info[pro Vince]: While True:for i3 in info[province][city]: p Rint ("\t\t", i3) area = input ("If you want to return to the parent menu Please enter B, exit please press Q, select the region:") if zone in info[        Province][city]:                    While True:for I4 in Info[province][city][area]:                                Print (i4) site = input ("To return to the parent menu, press B, exit please press Q, please select location:")                                    If site in Info[province][city][area]: print ("Choosing the right route for you ... \ n navigation starts")                                        back = input ("Last level menu, you can press B to return to the previous menu, exit please press Q:") If you = "B":                                        Pass Elif back = = "Q":                                Exit () elif site = = ' Q ': Exit ()                                    elif site = = ' B ': Break Else:                        Print ("Your input error, please re-enter:") elif area = = ' Q ': Exit () ELif area = = ' B ': Break Else:print ("Your input error, please re- New input: ") elif city = = ' Q ': Exit () elif city = = ' B ': Brea K Else:print ("Your input error, please re-enter:") elif province = = ' Q ': Exit () ELSE:PR int ("Your input error, please re-enter:")

Shopping Cart Program Optimization:
User Portal:
1, the product information exists in the document
2. Purchased goods, balance record
User Portal:
1, can add goods, modify the price of goods

3. Set operation

A collection is an unordered, non-repeating combination of data, and its main functions are as follows:
Go to the weight, turn a list into a set, and then automatically go heavy.
Relationship test, test the intersection of two sets of data, difference set, and the relationship between the set

3.1, set to remove the weight function
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. Relationship Testing
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. Basic operation (1) Add an item
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) Add multiple items
print(list_1.update([888,777,555]))执行结果:{1, 3, 4, 5, 6, 7, 9, 777, 555, 888}
(3) Delete the item, remove the non-existent item will be error, using discard will not error
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) Random deletion
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) Length of Set
list_1 = set([{1, 3, 4, 5, 6, 7, 9, 777, 555, 888}])print(len(list_1))执行结果:10
(6) Determine if X is a member of 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) Copy
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}

Reference link: Golden Horn king

Python Introductory chapter (iv) string, dictionary, collection

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.