一、上堂回顾
1.默写题目
1.创建一个非空集合,将其中的元素遍历出来
s1 = set([43,54,5]) #注意:通过dict创建set,使用的是dict中的key for element in s1: print(element)
2.创建一个非空列表,使用冒泡实现升序排序,使用选择实现降序排序
list1 = [4,5,46,65,3,243] #冒泡实现升序 for i in range(0,len(list1) - 1): for j in range(0,len(list1) - 1 - i): if list1[j] > list1[j + 1]: list1[j],list1[j + 1] = list1[j + 1],list1[j] #选择实现降序 for i in range(0,len(list1) - 1): for j in range(i + 1,len(list1)): if list1[i] < list1[j]: list1[i],list1[j] = list1[j],list1[i]
2.知识点回顾
二、String字符串
1.常用功能
1.1填充
代码演示:
#填充【了解】 #center(width[,fillchar]):返回一个指定宽度的居中字符串,width是填充之后整个字符串的长度, # fillchar是需要被填充的字符串,默认为空格 #char---->character字符 str1 = "hello" print(str1.center(20)) print(str1.center(20,"*")) #print(str1.center(20,"abc")) #TypeError: The fill character must be exactly one character long #注意:使用了center功能之后,生成了一个新的字符串,原字符串出现在中间,两边使用指定的字符进行填充 #注意:fillchar必须只有一个字符 #ljust(width[,fillchar]) 返回一个指定宽度的字符串,将原字符串居左对齐,width是填充之后整个字符串的长度, #l:left print(str1.ljust(20,"%")) #rjust(width[,fillchar]) 返回一个指定宽度的字符串,将原字符串居右对齐,width是填充之后整个字符串的长度, #r:right print(str1.rjust(20,"%")) #zfill(width)返回一个指定宽度的字符串,将原字符串居右对齐,width使用0填充 print(str1.zfill(20))
1.2查找
代码演示:
#查找【掌握】 str2 = "abcdefgh123hello" #find(str[,start,end]) :从左到右依次检测,str是否在原字符串中,如果存在,则返回位置 #特点:如果查找到,返回的是子字符串的第一个字符在原字符串中的下标;如果查找不到则返回-1 print(str2.find("hello")) #11 print(str2.find("e")) #4 print(str2.find("yyy")) #-1 print(str2.find("h",3,10)) #注意:如果子字符串在原字符串中出现多次,则只返回第一次查找到的下标 #rfind() :类似于find,只是从右往左检测 print(str2.rfind("hello")) #11 print(str2.rfind("e")) #12 #index():和find的用法基本相同,唯一的区别:find如果查找不到返回-1,但是index则直接报错 print(str2.index("hello")) #11 #print(str2.index("yyy")) #ValueError: substring not found #rindex() #max() :返回原字符串中的最大字母 #使用格式:max或者min(str) print(max(str2)) #min():返回原字符串中的最小字母 print(min(str2))
1.3提取
代码演示:
#提取: #strip(str) :使用str作为条件提取字符串,需要注意:只能去除两端的指定字符【trim】 str1 = "*****today is ******** a good day******" print(str1.strip("*")) #lstrip() :去除左边的指定字符串 print(str1.lstrip("*")) #rstrip():去除右边的指定字符串 print(str1.rstrip("*"))
1.4分割和合并
代码演示:
#分割和合并【掌握】:正则表达式 #split(str[,num]);使用指定字符串分割原字符串,返回一个列表【字符串转换为列表】 str1 = "today is a good day" print(str1.split(" ")) #['today', 'is', 'a', 'good', 'day'] str2 = "hello" #print(str1.split("")) #ValueError: empty separator #注意:使用split功能的时候,其中的分割字符串不能为空 #num表示分割符出现的次数 print(str1.split(" ",2)) #sliptlines(flag) 按照换行符【\n,\r,\r\n】分割,结果为列表 #falg可写可不写,False:忽略换行符,True:则表示保留换行符 s1 = """today is a good day """ print(s1.splitlines(True)) #['today\n', 'is\n', 'a\n', 'good\n', 'day\n'] print(s1.splitlines(False)) #['today', 'is', 'a', 'good', 'day'] #join(list);将原字符串作为连接符号,将列表中的元素连接起来,结果为一个字符串【列表转换为字符串】 str3 = "-" list1 = ["zhangsan","lisi","jack"] str4 = str3.join(list1) print(str4)
1.5替换
代码演示:
#替换【掌握】 #replace(old,new[,max]):将原字符串中的old字符串替换为new的字符串,如果指定了max,则替换的次数不超过max次 str1 = "today is a good day" #需求:将其中的good替换为bad #注意:替换之后仍然是生成了一个新的字符串 print(str1.replace("good","bad")) print(str1) str2 = "today is a good good good day" #注意:max:从左到右检测,只替换指定个数的字符串 print(str2.replace("good","bad",2)) #replaceAll()
1.6判断
代码演示:
#判断 #注意:全部返回的结果为布尔值 #isalpha():如果字符串至少有一个字符并且所有的字符都是字母的话,则返回True print("".isalpha()) print("abc".isalpha()) print("abc123".isalpha()) print("~~~~~~~") #isalnum():如果字符串至少有一个字符并且所有的字符是字母或者数字的话,则返回true print("".isalnum()) print("abc".isalnum()) print("abc123".isalnum()) print("~~~~~~~") #isupper():如果字符串中至少包含一个区分大小写的字符,并且所有的字符都是大写,则返回True print("abc".isupper()) print("123".isupper()) print("aBc".isupper()) print("ABC".isupper()) #True #islower() print("~~~~~~~") #istitle():如果字符串中的单词是标题化的,则返回True print("this is a test".istitle()) print("This is a test".istitle()) print("This Is A Test".istitle()) #True print("~~~~~~~") #isdigit()【掌握】:判断字符串中是否只包含数字,则返回True print("abc123".isdigit()) print("abc".isdigit()) print("123".isdigit()) #结合int("123") int("123abc")使用 print("~~~~~~~") #isnumeric():判断字符串中中是否只包含数字字符,则返回True print("abc123".isnumeric()) print("abc".isnumeric()) print("123".isnumeric()) print("~~~~~~~") #isdecimal():判断字符串中是否只包含十进制,则返回True print("2434".isdecimal()) print("454e4".isdecimal()) print("~~~~~~~") #isspace();判断字符串中是否只包含空格,则返回True print("abc 43".isspace()) print(" ".isspace()) #True
1.7前缀和后缀
代码演示:
前缀和后缀【掌握】 #结果为布尔值 #startswith(str[,beg=0,end=len(string)]) #判断原字符串是否是以指定子字符串开头的,如果beg和end指定值,则表示在指定的范围内判断 str1 = "helloghjshgj" print(str1.startswith("hello")) #endswith(str[,beg=0,end=len(string)]) print(str1.endswith("gj"))
1.8编解码
代码演示:
#字符串的编码和解码 #https://www.baidu.com/s?wd=%E5%8D%83%E9%94%8B&rsv_spt=1&rsv_iqid=0xdae3d65100023b6c&issp=1&f=8 #encode():将字符串转换为字节类型的过程 str2 = "hello 中文" print(str2.encode()) print(str2.encode("utf-8")) print(str2.encode("gbk")) byte11 = str2.encode("gbk") print(type(byte11)) #decode() :将字节类型转换为字符串的过程 print(byte11.decode("gbk"))
1.9ASCII码转换
代码演示:
#ASCII码转换 #ord():获取字符的整数表示 print(ord("A")) print(ord("a")) #chr():把编码转换为对应的字符 print(chr(65)) print(chr(97)) #需求:将hello转换为大写输出 s1 = "hello" s2 = "" for i in range(len(s1)): num = ord(s1[i]) num -= 32 ch = chr(num) print(ch) s2 += ch print(s2)
1.10字符串映射
代码演示:
#字符串的映射【ASCII码】 #maketrans(str1,str2):创建字符映射的转换表 #str1表示需要被转换的字符串,str2需要 转换的目标 t = str.maketrans("ac","68") print(t) #{97: 54, 99: 56} #translate(table) s3 = "hello abc" print(s3.translate(t)) #hello 6b8
1.11需要终点站掌握的功能
len() count() center() starswith() find()或者index() strip() replace() split() join() isdigit() ord()和chr()
1.12练习
代码演示:
#1.统计下面字符串中每个单词出现的次数,并生成一个字典,单词作为key,次数作为value str1 = "tomorrow is a good day tomorrow is a bad day tomorrow is a sunny day" """ 实现思路: 1.使用空格作为分隔符将字符串分隔,结果为list 2.遍历第一步中得到的list 3.将单词提取出来,去一个字典中判断 4.如果单词不存在,就以该单词作为key,1作为value存储到字典中 5.如果单词存在,将该单词对应的value递增1【修改键值对】 """ #方式一:get() list1 = str1.split(" ") #创建一个字典,备用 dict1 = {} for word in list1: value = dict1.get(word) #如果不存在则返回None if value == None: dict1[word] = 1 else: dict1[word] += 1 print(dict1) #方式二:成员运算符 dict2 = {} for word in list1: if word not in dict2: dict2[word] = 1 else: dict2[word] += 1 #2.给定一个时间【时分秒】,打印出该时间的下一秒 #例如:12:23:23 ------》12;23:24 #12:23:59---->12:24:00 #12:59:59----->13:00:00 timeStr = input("请输入正确格式的时间:") #将时分秒从字符串分隔出来 timeList = timeStr.split(":") h = int(timeList[0]) m = int(timeList[1]) s = int(timeList[2]) s += 1 if s == 60: m += 1 s = 0 if m == 60: h += 1 m = 0 if h == 24: h = 0 print("%d:%.2d:%.2d"%(h,m,s)) #%.2f #3.实现一个购物车功能 """ 1.引导用户选择商品 2.引导用户输入金额 3.加入购物车 4.查看购物车,计算余额 """ #商品列表 productList = [("book",50),("kindle",500),("iphone x",8000),("food",100)] #购物车 shoppingCar = [] saving = input("请输入金额:") #判断金额是否是纯数字 if saving.isdigit(): #将saving转换为数字类型 saving = int(saving) #不是添加一件商品就结束 while True: #打印商品信息,提供给用户选择 for i,p in enumerate(productList): print(i,":",p) #引导用户选择商品 choice = input("请输入商品编号[输入q退出]:") if choice.isdigit(): choice = int(choice) if choice >= 0 and choice <= len(productList): #将用户选择的商品从productList中取出来 item = productList[choice] #元组 #item[0]:商品名称 item[1];商品价格 if saving >= item[1]: #减少saving saving -= item[1] #将商品添加到购物车对应的list中 shoppingCar.append(item) else: print("余额不足") else: print("编号不存在") elif choice == "q": print("-----购物车中有如下商品------") for i in shoppingCar: print(i) print("你还剩余%d钱" %(saving)) break else: print("编号输入有误") else: print("invalid input")