STR1 formatted output% method The first%s+tuple%d+tuple
name = input(‘请输入你的姓名:‘)age = input(‘请输入你的年龄:‘)hobby = input(‘请输入你的爱好:‘)msg = ‘我叫%s,今年%d岁,爱好%s‘ % (name,int(age),hobby)
Second type% (name) +dict
dic = {‘name‘:‘老男孩‘,‘age‘:51,‘hobby‘:‘无所谓‘}msg = ‘我叫%(name)s,今年%(age)d岁,爱好%(hobby)s‘ % dicprint(msg)
Note in the formatted output of the simple display% with a percent solution
name = input(‘请输入你的姓名:‘)age = input(‘请输入你的年龄:‘)msg = ‘我叫%s,今年%d岁,学习进度为1%%‘ % (name,int(age))print(msg)
{}+format
Three ways to use
First usage: {}+ format + ()
s = ‘我叫{},今年{},爱好{}‘.format(‘MT‘,18,‘母牛‘)print(s)
Second usage: {num}+format+ ()
s = ‘我叫{0},今年{1},爱好{2},我依然叫{0},今年还是{1}‘ .format(‘MT‘,18,‘母牛‘)print(s)
The third key-value pair: {name}+format+dict
s = ‘我叫{name},今年{age},爱好{hobby}‘.format(age=18, name=‘MT‘, hobby=‘闷儿‘)print(s)
2 str index and slice index and slice s[start index: Cutoff index: Step]
s = ' I like Python '
Index
s1 = s[0]print(s1)s2 = s[2]print(s2)s3 = s[-1]print(s3)
Slice Gu Tou Disregard butt
s4 = s[0:3]print(s4)s41 = s[:3]print(s41)s5 = s[3:7]print(s5)s6 = s[:]print(s6)
Step
s7 = s[:5:2]print(s7)s8 = s[:7:3]print(s8)
Reverse Step
s7 = s[-1:-5:-1]print(s7)
Common Operation Method * * * First letter uppercase, other letters lowercase
s = ‘python‘s1 = s.capitalize()print(s1)
All uppercase, all lowercase
s2 = s.upper()s3 = s.lower()print(s2,s3)code = ‘aeQu‘.upper()your_code = input(‘请输入验证码‘).upper()if your_code == code: print(‘验证码输入成功‘)
* Center Center
s = ‘pthon‘s4 = s.center(30)print(s4)s4 = s.center(30,‘*‘)print(s4)
* * Case Flip
s5 = s.swapcase()print(s5)s = ‘woshiwangqingbin‘
Capitalize the first letter of each word (not separated by letters)
s6 =s.title()print(s6)
Decide what to start with and what to end with.
s = ‘wangqingbin‘startswith endswith()s7 = s.startswith(‘w‘)s71 = s.startswith(‘wq‘)s72 = s.startswith(‘wang‘)s73 = s.startswith(‘wangqing‘)s74 = s.startswith(‘q‘, 4)print(s74)print(s7,s71,s72,s74)
Remove the leading and trailing spaces, newline characters \n,tab \ t Remove the left space, line break, Tab Lstrip () to remove the right space, line break, Tab Rstrip () to remove the space on both sides strip ()
s = ‘ wangqingbin ‘s = ‘\nwangqingbin\t‘print(s)print(s.strip())print(s.lstrip())print(s.rstrip())
name = input(‘请输入用户名:‘).strip() if name == ‘wangqingbin‘: print(666) s = ‘,wangqingbin‘ print(s.strip(‘,wang‘))
Find index Search by element look up find
S.find (sub[, start[, end]), int or Return-1 on failure.
s = ‘wang‘print(s.find(‘w‘))print(s.find(‘a‘,3))print(s.find(‘x‘))
Index
Raise ValueError On Failure
print(s.index(‘x‘))
Count looks for the number of elements that appear to be sliced
s = ‘alexex‘print(s.count(‘e‘))print(s.count(‘ex‘))
Replace replacement
s = ’123王庆斌王庆斌123‘s1 = s.replace(‘王庆斌‘, ‘小粉嫩‘)print(s1)s2 = s.replace(‘王庆斌‘, ‘小粉嫩‘,1)print(s2)s3 = s.replace(‘王庆斌‘, ‘sb‘)print(s3)
Split split str---> List
s = ‘wang qing bin‘print(s.split(‘ ‘))s1 = ‘wang,qing,bin‘print(s1.split(‘,‘))s2 = ‘wangaqingsabin‘print(s2.split(‘a‘))s3 = ‘wangaqingsabin‘print(s3.split(‘a‘,1)) # 分割次数
* ISXXX
Print (Name.isalnum ()) #字符串由字母或数字组成
Print (Name.isalpha ()) #字符串只由字母组成
Print (Name.isdigit ()) #字符串只由数字组成
name=‘123a‘if name.isdigit(): name = int(name) print(name,type(name))else: print(‘您输入的由非数字元素‘)
Len
s = ‘fdsafdsaf‘print(len(s))count = 0s = ‘fdsafdsag‘print(s[0])print(s[1])print(s[2])while count < len(s): print(s[count]) count += 1for i in s: print(i)
List index, slice, step
li = [‘wang‘, 123, True, (1, 2, 3, ‘bin‘), [1, 2, 3, ‘qing‘,], {‘name‘:‘wang‘}]print(li[0])print(li[2])print(li[1:4])print(li[:5:2])print(li[-1:-3:-1])li = [1,‘a‘,‘b‘,‘a‘,2,3,‘wang‘]
Increase
appendli.append(‘bin‘)print(li.append(‘bin‘))li.append([1,2,3])name_list = [‘wang‘ ,‘qing‘,‘bin‘,‘cute‘,‘pi‘]while True: name = input(‘请输入新员工姓名:Q/q‘) if name.upper() == ‘Q‘:break else: name_list.append(name) print(‘已成功添加新员工%s‘ % name)print(name_list)print(li)
Insert Insertion
li.insert(2,‘小三‘)print(li)extend 迭代添加,到最后li.extend(‘ABC‘)li.extend([1,2,3])print(li)
Delete Pop by index
Li.pop () # Deletes the last one by default
Li.pop (1) # Delete the last one by default
s = li.pop(1)print(s)print(li)removeli.remove(‘a‘)print(li)
Clear Clear Contents
li.clear()print(li)
Del Delete list Slice delete
删除列表del liprint(li)切片删除del li[:3]del li[:3:2]print(li)
Change by index
print(li[1])li[1] = ‘A‘print(li[1])li[1] = [11,22,33,44]print(li)
Follow the slices to change
li[:3] = ‘Q‘print(li)li[:3] = ‘sonesb‘print(li)li[:3] = [11,22,33,44]print(li)
Check index, slice step, view
print(li[:3])
For loop
for i in li: print(i)l1 = [1, 2, 1, 7, 5, 4, 9, 8, 3]
Index is indexed by element
print(li.index(‘a‘))
Other ways to do this: sort from small to large, forward sort
l1.sort()print(l1)从大到小,反向排序l1.sort(reverse=True)print(l1)
Flip Reverse
l1.reverse()print(l1)
Len length
print(len(l1))li = [1,‘a‘,‘b‘,‘a‘,2,3,‘少年阿宾‘]countprint(l1.count(1))
Tuple Search
tu = (1,2,‘wang‘,‘qing‘)print(tu[:2])print(tu[2])for i in tu: print(i)
Son can not change, grandson may change
tu1 = (1,2,‘alex‘,[1,‘cte‘],(1,2,3),‘binge‘)tu1[3].append(‘1‘) print(tu1)li = [1,(1,2,3)]
Count () Len () index () Note:range as a list of numbers, range
for i in range(100): # [0,1,2,。。。99] print(i)for i in range(0,10,2): # [0,1,2,。。。99] print(i)for i in range(10,0,-1): # [0,1,2,。。。99] print(i)li = [2,3,‘12‘,4,5]for i in li: print(li.index(i))for i in range(0,len(li)): print(i)li = [1,2,3,[‘12‘,‘123‘,‘binge‘],4]‘‘‘for i in li: print(i) for ....‘‘‘
Dict
dic = {"name":"wqbin", "age":18, "sex":"male", }print(dic)
Hash table:
Print (hash (' name '))
Print (hash (' Fsagffsadgsdafgfdsagsadfgfag '))
Print (hash (' age '))
Increase
First: There is overwrite, none add
dic[‘hobby‘] = ‘girl‘print(dic)dic[‘name‘] = ‘wusir‘print(dic)
The second type of Setdeafult is added, and there is no change.
dic.setdefault(‘hobby‘)dic.setdefault(‘hobby‘,‘girl‘)dic.setdefault(‘name‘,‘ritian‘)print(dic)
By deleting
pop 有返回值print(dic.pop(‘age‘))print(dic)dic.pop(‘hobby‘) # 报错print(dic.pop(‘hobby‘, None)) # 返回你设定的值
Clear () Clear
dic.clear()print(dic)
Del
del dicprint(dic)del dic[‘name‘]print(dic)dic.popitem() # 随机删除 有返回值print(dic.popitem())print(dic)
Change
dic[‘name‘] = ‘斌哥‘print(dic)两个字典的改dic = {"name":"逼格","age":18,"sex":"male"}dic2 = {"name":"斌哥","weight":75}dic2.update(dic) # 将dic键值对,覆盖并添加到dic2print(dic)print(dic2)
Check
print(dic[‘name‘])print(dic[‘name1‘]) # 报错print(dic.get(‘name‘))print(dic.get(‘name1‘)) # 默认返回Noneprint(dic.get(‘name1‘,‘没有此键值对‘)) # 默认返回None
Other methods:
keys() values() items()print(dic.keys(),type(dic.keys()))print(dic.keys())
Keys ()
for i in dic.keys(): print(i)for i in dic: print(i)li = list(dic.keys())print(li)
VALUES ()
print(dic.values())for i in dic.values(): print(i)
Items ()
print(dic.items())for i in dic.items(): print(i) 特殊类型 dict 转化 成listprint(list(dic.keys()))
Concept: Assigning values separately
a,b = 2,3print(a,b)a,b = (2,3)print(a,b)a,b = [2,3]print(a,b)a = 4 ,b = 5a = 4b = 5a,b = b,aprint(a,b)print(dic.items())for k,v in dic.items(): print(k,v)
Nesting of dictionaries
DIC = {"Name_list": [' Zhang San ', ' Lisi ', ' Uncle Wang next Door '],
' Dic2 ': {' name ': ' Abingdon ', ' Age ': 12},
}
1, append an element to the list: ' Wang Wang '
l1 = dic[‘name_list‘]l1.append(‘旺旺‘)dic[‘name_list‘].append(‘旺旺‘)print(dic)
2, give the list Lisi all uppercase
print(dic[‘name_list‘][1].upper())dic[‘name_list‘][1] = dic[‘name_list‘][1].upper()print(dic)
3, add a key-value pair to the Dic2 dictionary: Hobby:girl.
dic[‘dic2‘][‘hobby‘] = ‘girl‘print(dic)
Exercise 1
1. Use while loop input 1 2 3 4 5 6 8 9 10
2. For all numbers of 1-100
sum = 0count = 1while count < 101: sum = sum + count count += 1 # count = count + 1 print(sum)
3. All odd numbers in output 1-100
count = 1while count < 101: print(count) count += 2 count = 1 while count < 101: if count % 2 == 1: print(count) count += 1
4, Beg 1-2+3-4+5 ... 99 of all numbers of the and
sum = 0count = 1while count < 100: if count % 2 == 0: sum -= count else: sum += count count += 1 print(sum)
5. User login (three chance retry)
username = ‘OldBoy‘password = ‘123‘i = 0while i < 3: name = input(‘请输入用户名:‘) pwd = input(‘请输入密码:‘) if name == username and pwd == password: print(‘登陆成功‘) break else: print(‘用户名或密码错误‘) i += 1
6, Write code: Calculate 1-2 + 3 ... + 99 in addition to the sum of all the numbers except 88?
sum = 0count = 0while count < 99: count += 1 if count == 88: continue if count % 2 == 0: sum -= count else: sum += countprint(sum)
7. User login (three chance of error) and display the number of remaining errors (hint: Format the string)
username = ‘wqb‘password = ‘123‘i = 0while i < 3: name = input(‘请输入用户名:‘) pwd = input(‘请输入密码:‘) if name == username and pwd == password: print(‘登陆成功‘) break else: print(‘用户名或密码错误,还剩%s机会‘ % (2-i)) i += 1 if i == 3: choice = input(‘是否还想在试试?Y‘) if choice == ‘Y‘: i = 0else: print(‘还要不要脸了....‘)
8. Implement an integer addition calculator (two numbers added):
such as: content = input (' Please enter content: ')
If user input: 5+9 or 5+ 9 or 5 + 9, then split and then calculate.
content = input("请输入内容:").strip().split(‘+‘)print(content)num = int(content[0]) + int(content[1])print(num)
9, there are several integers in the calculation of user input.
such as: content = input (' Please enter content: ') # such as Fhdal234slfh98769fjdla
content = input(‘请输入内容:‘)count = 0for i in content: if i.isdigit(): count += 1print(count)
content = input("input:")n = len(content)m = 0ls = []s = ‘‘while m < n: if content[m].isdigit(): s = s+content[m] if not content[m+1].isdigit(): ls.append(int(s)) m+=1 s = ‘‘ else: m+=1for x in ls: print(ls)
content = input("请输入你想输入的内容:")s = ‘‘ls = []n = len(content)m = 0num = 0while m<n: if content[m].isdigit(): s = s + content[m] if not content[m+1].isdigit(): ls.append( int(s)) s = ‘‘ m+=1 else: m+=1print(len(ls))for x in ls: print(type(x)) print(x)s = ‘fdsafdsa‘for i in s: print(i)else: print(666)
10, write code, such as the following table, as required to achieve each function.
Lis = [2,3, ' k ', [' qwe ', 20,[' K1 ', [' TT ', 3, ' 1 ']],89], ' ab ', ' adv ']
1) Turn the ' TT ' in the list Lis into uppercase (in two ways).
2) Change the number 3 in the list to the string ' 100 ' (in two ways).
3) Change the string ' 1 ' in the list to the number 101 (in two ways).
lis = [2,3,‘k‘,[‘qwe‘,20,[‘k1‘,[‘tt‘,3,‘1‘]],89],‘ab‘,‘adv‘]lis[3][2][1][0] = ‘TT‘print(lis)lis[3][2][1][0] = lis[3][2][1][0].upper()print(lis)lis[3][2][1][1] = ‘100‘print(lis)lis[3][2][1][1] = str(lis[3][2][1][1] + 97)print(lis)lis[3][2][1][2] = int(lis[3][2][1][2]) + 100print(lis)lis[3][2][1][2] = int(lis[3][2][1][2] + ‘01‘)print(lis)
11. Find the elements in the list Li, remove the spaces for each element, for I.strip ()
And find the beginning with ' a ' or ' a ',
And all the elements that end with ' C ',
and add it to a new list, and finally loop through the new list.
Li = [' Taibai ', ' alexc ', ' AbC ', ' Egon ', ' Ritian ', ' wusir ', ' AQC ']
For
li = [‘tso ‘,‘aC‘,‘AbC ‘,‘on‘,‘ck‘,‘ sir‘,‘ aqc‘]l1 = []for i in li: i = i.strip() if i[0].upper() == ‘A‘ and i[-1] == ‘c‘: l1.append(i)print(l1)l1 = []for i in li: i = i.strip() if (i.startswith(‘A‘) or i.startswith(‘a‘)) and i.endswith(‘c‘): l1.append(i)print(l1)
12, the development of sensitive word filter program, prompting the user to enter comments content,
If the user enters content that contains special characters:
List of sensitive words li = ["Cang teacher", "Tokyo Fever", "Enrique", "Yui Hatano")
Replace the sensitive words in the user input with a * * *, and add them to a list;
If the user enters content that does not have a sensitive vocabulary, add it directly to the list above
li = [‘苍老师‘,‘东京热‘,‘武藤兰‘,‘波多野结衣‘]ret = input(‘input:‘) # ***东京热武藤兰波多野结衣小泽玛利亚松岛枫l1 = []for i in li: ret = ret.replace(i,"*"*len(i)) # ******武藤兰波多野结衣小泽玛利亚松岛枫l1.append(ret)print(l1)lis = []for i in li: ret = ret.replace(i,len(i) * ‘*‘)lis.append(ret)print(lis)
13
av_catalog = { "欧美":{ "www.youporn.com": ["很多免费的,世界最大的","质量一般"], "www.pornhub.com": ["很多免费的,也很大","质量比yourporn高点"], "letmedothistoyou.com": ["多是自拍,高质量图片很多","资源不多,更新慢"], "x-art.com":["质量很高,真的很高","全部收费,屌丝请绕过"] }, "日韩":{ "tokyo-hot":["质量怎样不清楚,个人已经不喜欢日韩范了","verygood"] }, "大陆":{ "1024":["全部免费,真好,好人一生平安","服务器在国外,慢"] }}
1, give this ["a lot of free, the world's largest", "Quality General"] list the second position inserts an element: ' Very large '.
av_catalog[‘欧美‘][ "www.youporn.com"].insert(1,‘量很大‘)print(av_catalog)
2, will this ["high quality, really high", "all charges, the cock wire please bypass"] List of "All charges, cock wire please bypass" delete.
av_catalog[‘欧美‘]["x-art.com"].remove("全部收费,屌丝请绕过")print(av_catalog)
3, will this ["high quality, really high", "all charges, the cock wire please bypass"] List of "All charges, cock wire please bypass" delete.
4, this ["How quality is unclear, the individual already does not like Japan and South Korea fan", "Verygood"] List of "Verygood" all become uppercase.
5, add a key value to ' continent ' dictionary to ' 1048 ': [' One day is sealed ']
6, delete this "letmedothistoyou.com": ["mostly selfie, high-quality pictures many", "resources are not many, update slow"] key value pairs.
7, give this ["All free, really good, a good Life Peace", "server in Foreign, slow"] list of the first element, plus a sentence: ' Can climb down '
av_catalog[‘大陆‘][‘1024‘][0] = av_catalog[‘大陆‘][‘1024‘][0] + ‘可以爬下来‘print(av_catalog)av_catalog[‘大陆‘][‘1024‘][0] += ‘可以爬下来‘print(av_catalog)
14. The string "K:1|k1:2|k2:3|k3:4" is processed into a dictionary {' K ': 1, ' K1 ': 2 ...}
s = ‘k:1|k1:2|k2:3|k3:4‘li = s.split(‘|‘)dic = {}for i in li: dic[i.split(‘:‘)[0]] = int(i.split(‘:‘)[1])print(dic)dic = {‘k‘:1,‘k1‘:2}dic = {}for i in s.strip().split(‘|‘): # [‘k:1‘,‘k1:2‘。。。。] i = i.strip().split(‘:‘) # [‘k ‘,‘1‘] dic[i[0].strip()] = int(i[1])print(dic)
15. Element classification
The following value li= [11,22,33,44,55,66,77,88,99,90], saving all values greater than 66 to the first key in the dictionary, and saving the value less than 66 to the value of the second key. That is: {' K1 ': List of all values greater than 66, ' K2 ': List of all values less than 66}
dic = {‘k1‘:[],‘k2‘:[]}li= [11,22,33,44,55,77,88,99,90]for i in li: if i > 66: dic[‘k1‘].append(i) else: dic[‘k2‘].append(i)print(dic)li= [11,22,33,44,55,77,88,99,90]dic = {}for i in li: ····
16, the output product list, the user enters the serial number, displays the user to select the product
Product Li = ["Mobile phone", "Computer", "mouse pad", ' yacht ')
Requirements:
1: Page display serial number + product name, such as:
1 phones
2 pc ...
2: The user enters the selected item number and then prints the product name
3: If the user entered an incorrect serial number, you are prompted to enter it incorrectly and re-enter it.
4: User input Q or q, exit the program.
Li = ["Mobile phone", "Computer", "mouse pad", ' yacht ')
while True: for i in li: print(‘{}\t{}‘.format(li.index(i)+1,i)) num = input(‘请输入商品序号:q/Q退出‘).strip() if num.isdigit(): num = int(num) if num > 0 and num <= len(li): print(li[num - 1]) else: print(‘您输入的选项,超出范围,请重新输入‘) elif num.upper() == ‘Q‘:break else: print(‘输入的有非数字,请重新输入‘)
Str+tuple+list