[Learn Python quickly in 7 days - Day 3]
3 data types
布尔值(bool):True False
整型(int) :1 19 22 300
字符串(str) :"中国联通"
upper/lower/isdecimal/strip/lstrip/rstrip/replace/
join/split/center/ljust/rjust/zfill
len/索引/切片/for循环
列表(list) :[11,22,33] ["李冉","谢鹏","陈青",11, 22 ,True]
append/insert/remove/pop/clear/sort
len/索引/切片/for循环
元组(tuple) :(11,22,33) ("李冉","谢鹏","陈青",11, 22 ,True)
字典(dict) :{ "k1":123 , "k2":456 } {"n1":1,"N2":True}
n1 = "root"
res = n1.upper() # res = "ROOT"
n2 = "admin"
value = n2.upper() # value = "ADMIN"
data_list1 = [11,22,33,44]
data_list1.append(55) # 列表的功能,在列表的尾部追加某个值 [11,22,33,44,55]
data_list2 = [1,2,3]
data_list2.append(55) # 列表的功能,在列表的尾部追加某个值 [1,2,3,55]
Today’s summary:
- string type
- list type
- tuple type
1. String (str)
1.1 Definition
v = "xxxx"
1.2 Unique features
-
uppercase a.upper()
-
Lowercase a.lower()
-
Whether it is a number a.isdecimal
-
Replace a.replace("1","2")
-
Remove whitespace/left/right a.stript().lstript().rstript()
-
cutting
file_name = "day01 python基础编程入门.mp4" # 切割字符串后得到的是一个列表 # 0 1 # data_list = [ "day01 python基础编程入门" , "mp4" ] data_list = file_name.split(".")//flie.split(".") data_list[0] # "day01 python基础编程入门" data_list[1] # "mp4"
text = "武沛齐,root,[email protected],19" # 0 1 2 3 # ["武沛齐","root","[email protected]","19"] data_list = text.split(",") data_list[0] data_list[1] data_list[2] data_list[3]
-
Splicing
# 1.字符串相加 v1 = "鲁番吐" v2 = "大神" text = v1 + "是" + v2
# 2.字符串格式化 v1 = "鲁番吐" v2 = "大神" text = "{}是{}".format(v1,v2)
# 3.列表,里面有很多字符串,你想要让他们按照某个连接符拼接起来。注意事项:想要通过join去拼接,列表中必须都是字符串。 data_list = ["一","二","三","四"] res = "_".join(data_list) print(res) # "一_二_三_四" a = "_".join(list)
data_list = ["一","二","三","四"] res = ",".join(data_list) print(res) # "一,二,三,四"
data_list = ["一","二","三","四"] res = "".join(data_list) print(res) # "一二三四"
Note: If you want to join through join, the list must all be strings.
-
Convert string to byte type
字符串 unicode 字节 utf-8/gbk(文件存储、网络传输)
data = "中国联通" v1 = data.encode("utf-8")//"中国联通"压缩的值 print(v1) # b' \xe4 \xb8 \xad \xe5\x9b\xbd \xe8\x81\x94 \xe9\x80\x9a' # 01110010 10111000
text = v1.decode("utf-8")//"中国联通"解压的值 print(text) # "中国联通"
-
length complement
name = "宁摆场" text = name.center(13,"*")//居中,总长度为13 print(text) # "*****宁摆场*****"
name = "宁摆场" text = name.ljust(13,"#")//原值放左边 print(text) # "宁摆场##########"
name = "宁摆场" text = name.rjust(13,"#")//原值放右边 print(text) # "##########宁摆场"
-
The complement of length can only be padded with 0 on the left (0 is padded in front of a binary string)
name = "吐鲁番" v1 = name.zfill(10)//补足,总长度为10,,,,zfill print(v1) # "0000000卢红萍"
data = "10101" res = data.zfill(8) print(res) # "00010101"
Practice questions
-
Write code to implement it, prompting the user to enter text, you can judge whether the text starts with "China", enter: Chinese, otherwise foreigner.
text = input(">>>") if text.startswith("中国")://a.startswith("中国') print("中国人") else: print("外国人")
-
Write code to implement it, prompt the user to enter text, and replace upper with lower in the text.
text = input(">>>") res = text.replace("上","下")//替换a.replace("上","下") print(res)
-
Prompts the user to enter two numbers to add, for example: 5+2, 6+9 format (do not consider yy+77).
# 0 1 data_list = [11, 9] data_list[0] data_list[1]
text = input(">>>") # "5+9"//5+9 data_list = text.split("+") # ["5","9"]//data = a.split("+") res = int(data_list[0]) + int(data_list[1])//int(data[0]) + int(data[1]) print(res)
-
Prompts the user to input two numbers to add, for example: 5+2, 6+9, Hello+9. If it is judged that they are all numbers, the numbers will be added. As long as any one is not a number, an input error will be prompted.
text = input(">>>") # "5+9" data_list = text.split("+") # ["5","9"] if data_list[0].isdecimal() and data_list[1].isdecimal()://isdecimal() res = int(data_list[0]) + int(data_list[1]) print(res) else: print("输入错误")
-
Queue to buy tickets
# ["罗小春","谢鹏",龚星云] name_list = [] name_list.append("罗小春") name_list.append("谢鹏") name_list.append("龚星云") # name_list = ["罗小春","谢鹏",龚星云]
# 1.循环让用户输入姓名(q/Q终止),每输入一个姓名都追加到列表中。 # 2.输入q退出之后,将所有的人员姓名通过逗号连接成字符串并输出。
user_list = [] while True://while True:a = input() name = input("请输入姓名:")//if a.upper() == "Q" if name.upper() == "Q": break user_list.append(name) res = ",".join(user_list)//b = ",".join(user_list) print(res)
1.3 Public functions
-
Length a = len("str")
name = "欧阳娜娜" res = len(name) print(res) # 4
v1 = len("陆梅yy8899") print(v2) # 8
-
index
# 0 1 2 3 4 5 6 7 8 9 10 11 text = "我 要 学 习 P y t h o n 编 程" text[0] # "我" text[8] # "o" text[10] # "编" v1 = 3 text[v1] # "习" text[100] # 报错,不能超出范围取值 v2 = len(text) - 1 # 12 text[v2] # "程"
text = "我要学习python编程" index = 0 while index < len(text): print(text[index]) index += 1
# 0 1 2 3 4 5 6 7 8 9 10 11 # -3 -2 -1 text = "我 要 学 习 P y t h o n 编 程" text[-1] # "程"
-
Slicing // Take before and after without taking, the string cannot be changed, slicing is a copy of the original string cut out
# 0 1 2 3 4 5 6 7 8 9 10 11 # -3 -2 -1 text = "我 要 学 习 P y t h o n 编 程" text[0:2] # "我要" text[2:8] # "学习Pytho" text[2:-1] # "学习Python编" text[2:] # "学习Python编程"//从2开始到最后 text[:-1] # "我要学习Python编"//从开始到编 text[:] # "我要学习Python编程"//全部 # 注意:1.前取后不取; 2.索引位置是从0开始。
num = 189 # 1.转换成二进制的字符串 bin_string = bin(num) # '0b10111101' # 2.不要0b, data="10111101" data = bin_string[2:] # 3.将二进制字符串补足16位,在他的前面补0 result = data.zfill(16) print(result) # "0000000010111101"
-
cycle
给你一个字符串 data = "我要学习Python编程" ,让你循环字符串中的每个元素。 - while循环+索引 - for循环
-
while loop
data = "我要学习Python编程" index = 0 while index < len(data): char = data[index] print(char) index += 1
-
for loop, get it directly.
data = "我要学习Python编程"//字符串 for item in data://for i in data: print(i) print(item)
data = [11,22,33,44,55,66]//列表 for item in data: print(item) .. .. ...
# range函数作用,帮助你生成一个数字列表。从0开始,前取后不取 v1 = range(5) # [0,1,2,3,4]//0-4 v2 = range(5,10) # [5,6,7,8,9]//5-9 v3 = range(5,10,2) # [5,7,9]//5,7,9 v5 = range(10,0,-1) # [10,9,8,7,6,5,4,3,2,1]//10-1
for item in range(5): # [0,1,2,3,4] print(item) for item in range(5,10): # [5,6,7,8,9] print(item) for item in range(10,0,-1): # [10,9,8,7,6,5,4,3,2,1] print(item)
# 请实现获取字符串中的每个元素并输出。 data = "我要学习Python编程" # 方式1 index = 0 while index < len(data): char = data[index] print(char) index += 1 # 方式2 for item in data: print(item) # 方式3 for idx in range(len(data)): # [0,1,2,3,4,5,6,7,8,9,10,11] char = data[idx] print(char)
-
Practice questions
-
The for loop outputs each character of
message = "伤情最是晚凉天,憔悴厮人不堪言"
.message = "伤情最是晚凉天,憔悴厮人不堪言" for item in message: print(item)
-
for loop + range realizes outputting each character in
message = "伤情最是晚凉天,憔悴厮人不堪言"
in reverse order.message = "伤情最是晚凉天,憔悴厮人不堪言" for i in range(len(message)-1, -1, -1): print(message[i])
-
Let the user input a piece of text and count the number of times "wave" appears in the output text.
text = input(">>>") count = 0 for item in text: if item == "浪": count += 1 data = "浪出现的次数:{}次".format(count) print(data)
-
Write code to implement:
- Prompts the user to enter content, which includes: as8dfa9784adfasdf sofa cushion
- Extract the number from the user input: 89784
- Convert the extracted number to an integer, and then convert the integer to a binary string.
- Remove the 0b in front of the binary string.
- Output the binary string after removing 0b.
text = input(">>>") # abc11uu98f3 char_list = [] # ["1","1","9","8","3"] for item in text: if item.isdecimal(): char_list.append(item) num_string = "".join(char_list) # "11983" num_int = int(num_string) # 11983 bin_string = bin(num_int) # 0b110101010010101 res = bin_string[2:] print(res)
text = input(">>>") # abc11uu98f3 char_list = [] # ["1","1","9","8","3"] for item in text: if item.isdecimal(): char_list.append(item) res = bin(int("".join(char_list)))[2:]//bin(int("".join(char_list)))[2:] print(res)
-
Query all files in a directory on your own computer and determine whether the file extension is: png or PNG. If so, output it.
import os// #mac系统 # ['[email protected]', '[email protected]', '[email protected]', 'demo.py', '.idea'] data_list = os.listdir("/Users/wupeiqi/PycharmProjects/gx_day03")//拿到该目录下所有文件夹和文件,并将其文件名放在列表中 for file_name in data_list: print(file_name)//换行 # win import os data_list = os.listdir(r"C:\xx\xx\xx")//拿到该目录下所有文件夹和文件,并将其文件名放在列表中 for file_name in data_list: print(file_name) # "字符串"
import os data_list = os.listdir("/Users/wupeiqi/PycharmProjects/gx_day03") for file_name in data_list: # print(file_name) # "字符串" if file_name.upper().endswith(".PNG")://文件名变成大写的结尾是否为PNG print(file_name)
import os data_list = os.listdir("/Users/wupeiqi/PycharmProjects/gx_day03") for file_name in data_list: # text = "中国联通" # text[-1] # name_list = ["WX20201115-092707@2x","png"] # name_list[-1] name_list = file_name.split(".") # [email protected] if name_list[-1].upper() == "PNG": print(file_name)
2. List
A list is an ordered and mutable container whose elements can be of many different data types.
2.1 Definition
data_list = [ 11, 22, "中国俩通", True]
data = []
data.append(11)
data.append(999)
Note: The list is a variable type, and most functions operate on the original list.
2.2 Unique functions
-
addition
data_list = [] data_lista.append(11) data_lista.append("wupeiqi")
hobby_list = [] while True: hobby = input("请输入你的爱好:") if hobby.upper() == "Q": break hobby_list.append(hobby)//list.append()
-
Insert, insert the data into that location.
# 0 1 2 3 user_list = ["陈清","李阳金","马其坤","刘东"] user_list.insert(1,"孟东珏")//插入到索引为1的地方 print(user_list) # ["陈清", "孟东珏", "李阳金","马其坤","刘东"]
user_list = ["李柔","周雪梅","卢慧","孟东珏","陈清","李阳金","马其坤","刘东"] user_list.insert(0,"孟东珏") user_list.insert(0,"卢慧") user_list.insert(0,"周雪梅") user_list.insert(0,"李柔")
# 案例:排队 user_list = [] while True: name = input("请输入姓名:") if name.upper() == "Q": break if name.startswith("刁")://输入名字前有刁放第一位 user_list.insert(0,name) else: user_list.append(name)
-
delete (value delete)
user_list = ["李柔","周雪梅","卢慧","孟东珏","陈清","李阳金","马其坤","刘东"] user_list.remove("陈清清")//list.remove(删除元素),删除从左到右的第一个符合要求的元素 # ["李柔","周雪梅","卢慧","孟东珏","李阳金","马其坤","刘东"] print(user_list)
Note: When using remove to delete an element of the list, if the element does not exist, an error will be reported.
user_list = ["李柔","周雪梅","卢慧","孟东珏","陈清","李阳金","马其坤","刘东"] if "陈清清" in user_list: user_list.remove("陈清清")
# 抽奖小程序 import random # 1.构造200名员工并存放在列表中。 user_list = [] for i in range(1, 201): name = "工号-{}".format(i) user_list.append(name) # 2.随机抽取1名员工,发奖金20w # 随机去user_list列表中抽取一个数据 data = random.choice(user_list)//randon.choice()随机抽取一个数据 print("获得3等奖的是:", data) # 将用户在列表中删除 user_list.remove(data) # 随机去user_list列表中抽取一个数据 data = random.choice(user_list) print("获得2等奖的是:", data)
-
Delete(index position)
user_list = ["李柔","周雪梅","卢慧","孟东珏","陈清","李阳金","马其坤","刘东"] user_list.pop(1)//根据索引位置删除元素 # ["李柔", "卢慧","孟东珏","陈清","李阳金","马其坤","刘东"] print(user_list)
user_list = ["李柔","周雪梅","卢慧","孟东珏","陈清","李阳金","马其坤","刘东"] user_list.pop()//默认删除尾部元素 # ["李柔","周雪梅","卢慧","孟东珏","陈清","李阳金","马其坤"] print(user_list)
user_list = ["李柔","周雪梅","卢慧","孟东珏","陈清","李阳金","马其坤","刘东"] # 1.在原列表中删除指定索引位置的值 # 2.将刚删除的数据获取到并赋值前面的变量。 data = user_list.pop(1) print(data) # "周雪梅" print(user_list) # ["李柔", "卢慧","孟东珏","陈清","李阳金","马其坤","刘东"]
# 排队买火车票 # 1.排队买票的人 user_queue = [] while True: name = input("上海~北京火车票,购买者姓名(Q/q):") if name.upper() == "Q": break user_queue.append(name) # 2.放了3张票 for i in range(3): username = user_queue.pop(0) message = "恭喜{},购买成功".format(username) print(message) # 3.通知其他人,无票,请选择其他出行方式 others = ",".join(user_queue) data = "票已售罄,请以下人员选择其他出行方式:{}".format(others) print(data)
-
clear the list
user_list = ["李柔","周雪梅","卢慧","孟东珏","陈清","李阳金","马其坤","刘东"] user_list.clear()//list.clear() print(user_list) # []
-
Sorting list elements
num_list = [11, 22, 8, 12, 99, 231, 1] num_list.sort()//排序,默认从小到大 print(num_list) # [1, 8, 11, 12, 22, 99, 231]
num_list = [11, 22, 8, 12, 99, 231, 1] num_list.sort(reverse=True)//从大到小 print(num_list) # [231, 99, 22, 12, 11, 8, 1]
Chinese sorting rules: unicode (understand)
user_list = ["页子", "青青", "韦神", ] user_list.sort() print(user_list) # ['青青', '韦神', '页子']
2.3 Public functions
-
length//list length
data_list = [11,22,33,44] res = len(data_list) print(res) # 4
-
index
# 0 1 2 3 4 5 6 7 # ... -2 -1 user_list = ["李柔","周雪梅","卢慧","孟东珏","陈清","李阳金","马其坤","刘东"] # 获取值 user_list[0] user_list[2] user_list[ len(user_list)-1 ] user_list[-1] # 修改//列表可以修改,所以利用索引可以修改 user_list[1] = "马冬梅" print(user_list) # ["李柔","马冬梅","卢慧","孟东珏","陈清","李阳金","马其坤","刘东"] # 删除 del user_list[5] print(user_list) # ["李柔","周雪梅","卢慧","孟东珏","陈清",马其坤","刘东"]
-
slice
user_list = ["李柔","周雪梅","卢慧","孟东珏","陈清","李阳金","马其坤","刘东"] # 读取一部分 user_list[0:4] # ["李柔","周雪梅","卢慧","孟东珏"] user_list[0:-1] # ["李柔","周雪梅","卢慧","孟东珏","陈清","李阳金","马其坤"] user_list[2:] # ["卢慧","孟东珏","陈清","李阳金","马其坤","刘东"] user_list[:] # ["李柔","周雪梅","卢慧","孟东珏","陈清","李阳金","马其坤","刘东"] # 修改一部分 user_list = ["李柔", "周雪梅", "卢慧", "孟东珏", "陈清", "李阳金", "马其坤", "刘东"] user_list[0:2] = [11, 22, 33, 44]//二换四 # [11, 22, 33, 44, '卢慧', '孟东珏', '陈清', '李阳金', '马其坤', '刘东'] print(user_list) # 删除 user_list = ["李柔", "周雪梅", "卢慧", "孟东珏", "陈清", "李阳金", "马其坤", "刘东"] del user_list[2:4] # ['李柔', '周雪梅', '陈清', '李阳金', '马其坤', '刘东'] print(user_list)
-
for loop
user_list = ["李柔","周雪梅","卢慧","孟东珏","陈清","李阳金","马其坤","刘东"] for item in user_list: print(item)
user_list = ["李柔","周雪梅","卢慧","孟东珏","陈清","李阳金","马其坤","刘东"] for i in range(len(user_list)): print(i) print( user_list[i] )
user_list = ["李柔", "周雪梅", "卢慧", "孟东珏", "陈清", "李阳金", "马其坤", "刘东"] for i in range(len(user_list)): data = "{}-{}".format(i, user_list[i]) print(data)
2.4 Nesting
A list is a "container", and many things can be placed in the container.
data_list = [11,22,"武沛齐",["中国联通","中国移动"],666, True]
data_list = [
"梁吉宁",
"赵建先",
'root',
[999,888,777,666],
'admin',
666,
["周杰伦","刘欢","林俊杰","王一博"],
["刘翔","周琦",["姚明","王治郅","巴蒂尔"],"赵继伟"],
]
res = data_list[2].upper()//生成新的值赋给res
print(data_list) # 中的root是小写的。
print(res) # ROOT
# 取值
data_list[1] "赵建先"
data_list[1][-1] "先"
data_list[-1][2][-2] "王治郅"
# 操作
data_list[0] = "李柔"
data_list[3][-1] = "666"
data_list[4][0] = "A" # 报错? admin-> Admin//报错,字符串无法修改
print(data_list)
# 操作
data_list.append(123)
data_list[-1].append("大侄子")//不会报错,把元素加在"赵继伟"后面
data_list[-1][2].append("大侄子")//"巴蒂尔"后面
# 列表是一个可变类型,列表中的常见功能是对列表本身进行操作。
Practice questions
-
User registration, loop prompts the user to enter the user name and password, and terminates if Q or q is entered when the user name is entered.
user_list = [ ["用户名A","密码A"] , ["用户名A","密码A"], ["用户名A","密码A"] ]
user_list = [] while True: user = input(">>>") if user.uppper() == 'Q': break pwd = input(">>>") item = [ user, pwd ] user_list.append(item)
-
Loop out product information
goods = [ ["飞机",3000], ["迫击炮",1000], ["AK47",300], ["m6",600], ] for i in range(len(goods)): message = "{} {}".format(i, goods[i][0] ) print(message)
# 输出 0 飞机 1 迫击炮 2 AK47 3 m6
-
The product information is output in a loop. The user enters the serial number. The product information is obtained according to the serial number entered by the user and output. The format is as follows:
您选择的商品是xx,价格是xx。
goods = [ ["飞机", 3000], ["迫击炮", 1000], ["AK47", 300], ["m6", 600], ] # 1.展示商品信息 for i in range(len(goods)): message = "{} {}".format(i, goods[i][0]) print(message) # 2.用户选择 choice = input("请选择:") if choice.isdecimal(): # 整型 choice = int(choice) # 范围 if choice >= 0 and choice < len(goods): data_info = goods[choice] message = "您选择的商品是{},价格是{}。".format(data_info[0], data_info[1]) print(message) else: print("序号输入不合法") else: print("输入必须是整数")
goods = [ ["飞机", 3000], ["迫击炮", 1000], ["AK47", 300], ["m6", 600], ] # 1.展示商品信息 for i in range(len(goods)): message = "{} {}".format(i, goods[i][0]) print(message) # 2.用户选择 choice = input("请选择:") if choice.isdecimal(): # 整型 choice = int(choice) # 范围 if 0 <= choice < len(goods): data_info = goods[choice] message = "您选择的商品是{},价格是{}。".format(data_info[0], data_info[1]) print(message) else: print("序号输入不合法") else: print("输入必须是整数")
-
Here are some sensitive words for you
key_list = ["日本","台湾","美国","新疆"]
text = input("请输入评论:")
# 将评论的内容中出现的关键字全部替换成 **
key_list = ["日本","台湾","美国","新疆"]
text = input("请输入评论:") # "你美国和日本人的混血"
for key in key_list:
text = text.replace(key,"**")//替换,replace
print(text)
3. Tuple
A list is an ordered and mutable container whose elements can be of many different data types.
A tuple is an ordered and immutable container whose elements can be of many different data types.
data = []
data.append(11)
data.append(234)
# 定义了一个元组,元组中有三个元素。不能删,不能改,不能添加
data = (11,22,33)
3.1 Definition
v1 = (11,22,33)
v2 = (11,22,True,"武沛齐")
v3 = (11,22,True,(55,66), "武沛齐",[11,22,33,44])
The number of tuples cannot be modified; the elements of a tuple cannot be replaced with other values.
Note: error-prone points in tuples.
v1 = (11,22) # 正确,元组
v2 = (33,44,) # 正确,元组,逗号可有可无
v3 = (666) # v3 = 666
v4 = (666,) # v4 = 元组,只有一个元素666
If there is only one element in the tuple and there is no comma at the end, it is not a tuple, but the value after removing the parentheses.
1. 比较一下三个值的区别:
v1 = (1)
v2 = 1
v3 = (1,)
2.比较一下三个值的区别:
v1 = ( (1),(2),(3) )
v2 = ( 1, 2, 3 )
v3 = ( (1,), (2,), (3,) )
3.2 Unique functions
none
3.3 Public functions
-
length
v1 = (11,22,True,"武沛齐") res = len(v1) print(res) # 4
-
Index (read only)
v1 = (11,22,True,"武沛齐") v1[0] v1[2] v1[-1]
-
Slicing //One point copies a new value
v1 = (11,22,True,"武沛齐") v2 = v1[1:3] print(v2) # (22,True) v3 = v1[1:] print(v3) # (22,True,"武沛齐")
-
for loop
v1 = (11,22,True,"武沛齐") for item in v1: print(item)
v1 = (11,22,True,"武沛齐") for i in range(len(v1)): print(i) print( v1[i] )
3.4 Nesting
data = (
11,
22,
True,
("陆梅","吴国锋",[1,2,3,4])
"武沛齐",
["陈清","马其坤","李冉"]
)
data[-2] # ""武沛齐""
data[-3][0] # "陆梅"
data[-3][-1][0] # 1
# 元组的元素不可以被替换,元素个数也不允许修改。
data[0] = 123 # 报错
data[-1] = 666 # 报错
data[-1][0] = "张电摩" # 正确,整体未被替换
Practice questions
-
First there is a tuple, which stores some data, for example:
data = ("京A99110","沪B88776","黑A88776",...) # 1.获取所有京牌的车牌并放到一个列表中。 # 2.输出列表;再输出京牌的个数。
data = ("京A99110", "沪B88776", "黑A88776", "京A11111","京A111331") result = [] for item in data: if item.startswith("京"): result.append(item) print(result) print(len(result))
-
Create a deck of playing cards (excluding kings and kings)
color_list = ["红桃","黑桃","方片","梅花"] # num_list = range(1,14) num_list = [1,2,3,4,5,6,7,8,9,10,11,12,13] # 获取一副扑克牌 # result = [ ("红桃",1),("红桃",2)....,("黑桃",1)..("梅花",13) ]
color_list = ["红桃", "黑桃", "方片", "梅花"] num_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] result = [] for color in color_list: # print(color) # color="黑桃" for num in num_list: item = (color, num) result.append(item) print(result)