python基本数据类型(2)
本节内容:基本数据类型
1. 数字
2.字符串
3.列表
4.元组
5.字典
6.格式化输出
7.作业
1、数字(int)
数字主要是用于计算用的,使用方法并不是很多:
2、字符串
2.1 存储少量的数据,进行简单的操作
msg = ''' 今天我想写首小诗, 歌颂我的同桌, 你看他那乌黑的短发, 好像一只炸毛鸡。 ''' print(msg)
>>>输出
今天我想写首小诗,
歌颂我的同桌,
你看他那乌黑的短发,
好像一只炸毛鸡。
2.2 字符串可以相加
s1 = 'alex' s2 = 'boss' print(s1 + s2)
>>>输出
alexboss
2.3 字符串相乘是字符串乘数字
print('坚强'*8)
>>>输出
坚强坚强坚强坚强坚强坚强坚强坚强
2.4 索引与切片
s = 'alexwusirritian' s1 = s[0] print(s1,type(s1)) s2 = s[2] print(s2) s3 = s[-1] print(s3) s4 = s[-2] print(s4)
----------------------------
切片:
#切片
#切片 顾头不顾腚
s5 = s[0:4]
s5 = s[:4]
print(s5)
s6 = s[4:9]
print(s6)
s7 = s[:]
print(s7)
s8 = s[:5:2]
print(s8)
s9 = s[-1:-5:-1]
print(s9)
#切片:s[起始索引:结束索引+1:步长]
2.5 字符串的常用方法
2.5.1 首字母大写,其余字符小写
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
s = 'alexWUsir' s1 = s.capitalize() print(s1) >>>输出 Alexwusir
2.5.2 大小写翻转
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
s = 'alexWUsir' s2 = s.swapcase() print(s2) >>>输出 ALEXwuSIR
2.5.3 title非字母隔开的每个单词的首字母大写
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
s = 'alex wusir*taibai2ritian' s3 = s.title() print(s3) >>>输出 Alex Wusir*Taibai2Ritian
2.5.4 设置总长度并居中
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
s = 'alex wusir*taibai2ritian' s4 = s.center(30,'*') print(s4) >>>输出 ***alex wusir*taibai2ritian***
2.5.5 全部转化为大写
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
s = 'alex wusir*taibai2ritian' s5 = s.upper() print(s5) >>>输出 ALEX WUSIR*TAIBAI2RITIAN 示例: code = 'AwEqr' username= input('请输入用户名:') your_code = input('请输入验证码:') if username == 'alex' and your_code.upper() == code.upper(): print('验证成功') >>>输出 请输入用户名:alex 请输入验证码:aweqr 验证成功
2.5.6 判断开头与结尾
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
a4 = "dkfjdkfasf54" startswith 判断是否以...开头 endswith 判断是否以...结尾 ret4 = a4.endswith('jdk',3,6) # 顾头不顾腚 print(ret4) # 返回的是布尔值 ret5 = a4.startswith("kfj",1,4) print(ret5)
2.5.7 默认去除字符串前后的空格,换行符,制表符
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
s = ' alexWUsir\t' s7 = s.strip() print(s7) >>>输出 alexWUsir ss = 'abclaonanhaiq' ss1 = ss.strip('abqc') print(ss1) >>>输出 laonanhai 示例: username = input('>>>').strip() password = input('>>>').strip() if username == '老男孩' and password == '123': print('登录成功')
2.5.8 替换
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
s = 'alex 分甘共苦老地方 alex 风刀霜剑卡乐芙' s8 = s.replace('alex', 'boss') s9 = s.replace('alex', 'boss',1) print(s8) print(s9) >>>s8输出 boss 分甘共苦老地方 boss 风刀霜剑卡乐芙 >>>s9输出 boss 分甘共苦老地方 alex 风刀霜剑卡乐芙
2.5.9 分隔
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
s1 = 'alex wusir taibai ritian' s2 = 'alex,wusir,taibai,ritian' s3 = 'alexwusirtaibairitian' s4 = 'alexwusirtaibairitian' l1 = s1.split() # 默认以空格分隔 l2 = s2.split(',') l3 = s3.split('a') l4 = s4.split('a',2) print(l1) print(l2) print(l3) print(l4)
2.5.10 join 列表转分隔成字符串
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
l1 = ['alex', 'wusir', 'ritian'] s10 = ' '.join(l1) print(s10,type(s10)) >>>输出 alex wusir ritian <class 'str'>
2.5.11 通过元素找索引
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
s = 'alexwausir' find 找不到返回-1 index找不到会报错 s11 = s.find('e') s12 = s.find('ex') print(s11,type(s11)) print(s12,type(s12)) s11 = s.find('a',1) print(s11) print(s.find('A')) print(s.index('A'))
2.5.12 format格式化输出用法
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
s = "我叫{},今年{},爱好{}" 第一种用法 s12 = s.format('太白', '25', '女') print(s12) 第二种用法 s1 = "我叫{0},今年{1},爱好{2},我依然叫{0}" s13 = s1.format('太白', '25', '女') print(s13) 第三种用法 s3 = "我叫{name},今年{age},爱好{hobby}" s14 = s3.format(age=25,hobby='girl',name='太白') print(s14)
2.6 公共方法
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#len 测量个数 print(len(s)) #count print(s.count('a')) # name = '123' print(name.isalnum()) #字符串由字母或数字组成 print(name.isalpha()) #字符串只由字母组成 print(name.isdigit()) #字符串只由数字组成
3、列表
# 按照索引取值,与元素本身的数据类型一致 # 按照切片取值,取出来的是小列表。 li = [1, (2, 3), 2, 3, 4, 5, 6,] l1 = li[:3] print(l1) print(li[0],type(li[0])) print(li[1],type(li[1])) l2 = li[:] print(l2)
3.1 增
3.1.1 追加
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
l = ['WuSir', 'alex', 'OldBoy', 'barry'] l.append('景女神') l.append(1) print(l) >>>输出 ['WuSir', 'alex', 'OldBoy', 'barry''景女神']
3.1.2 根据索引插入
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
l = ['WuSir', 'alex', 'OldBoy', 'barry'] l.insert(1, '葫芦') print(l) >>>输出 ['WuSir','葫芦', 'alex', 'OldBoy', 'barry']
3.1.3 extend
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
l = ['WuSir', 'alex', 'OldBoy', 'barry'] l.extend('abc') l.extend([1, '2122', 56]) print(l) >>>输出 ['WuSir', 'alex', 'OldBoy', 'barry', 'a', 'b', 'c', 1, '2122', 56]
3.2 删
3.2.1 按照索引删除
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
l = ['WuSir', 'alex', 'OldBoy', 'barry'] ret = l.pop(1) print(l) >>>输出 ['WuSir', 'OldBoy', 'barry']
3.2.2 按照元素删除
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
l = ['WuSir', 'alex', 'OldBoy', 'barry'] l.remove('alex') print(l) >>>输出 ['WuSir', 'OldBoy', 'barry']
3.2.3 清空列表
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
l = ['WuSir', 'alex', 'OldBoy', 'barry'] l.clear() print(l) del l print(l) del l[1] print(l) del l[:3] print(l)
3.3 改
3.31 按照索引改
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
l = ['WuSir', 'alex', 'OldBoy', 'barry'] l[0] = '日天' print(l) >>>输出 ['日天', 'alex', 'OldBoy', 'barry'] l[2] = '老男孩' print(l) >>>输出 ['WuSir', 'alex', '老男孩', 'barry']
3.3.2 按照切片去改
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
l[:3] = 'abcdgfdljgkfdgjlfdlgjfdsaklfdjskladsfj' l[:3] = 'a' l[:3] = [11, 22, 33, 44] #加步长 必须一一对应 l[:3:2] = 'ab' print(l)
3.4 查
3.4.1 按照索引,切片(步长)
3.4.2 for 循环遍历
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
l = ['WuSir', 'alex', 'OldBoy', 'barry'] for i in l: print(i) >>>输出 WuSir alex OldBoy barry
3.5 正序、倒序、翻转
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
l1 = [1, 9, 8, 4, 3, 2, 6,] l1.sort() # 正序排序 print(l1) l1.sort(reverse=True) # 倒叙排序 print(l1) l1.reverse() # 翻转 print(l1)
3.6 列表的嵌套
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
l1 = [1, 2, 'alex', ['WuSir', 'taibai', 99], 6] # 1,将alex该成Alex l1[2] = l1[2].capitalize() # 2,将'WuSir'变成全部大写。 l1[3][0] = l1[3][0].upper() print(l1) # 3,99让其通过数字加1的方式变成 '100'. l1[3][-1] = str(l1[3][-1] + 1) print(l1)
4、元组
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#元组 只读列表。 tu = (1, 2, 33, 'alex') print(tu[1]) >>>输出 2 print(tu[:-1]) >>>输出 (1, 2, 33) for i in tu: print(i) >>>输出 1 2 33 alex tu1 = (1, 2, [1, 3,], 4) tu1[2].append(666) print(tu1) >>>输出 (1, 2, [1, 3, 666], 4)
4.1 range
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
print(range(100)) for i in range(100): print(i) for i in range(1,11): print(i) for i in range(2, 101, 2): print(i) for i in range(100,0,-1): print(i) l1 = [1, 2, 3, 4, 5, 'alex'] for i in range(len(l1)): print(i)
5、字典的增删改查
5.1 增
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
dic = { 'name': '老男孩', 'age': 10000, 'sex': '男', } dic['hobby'] = 'old_girl' # 无责增加,有责修改。 dic['name'] = 'alex' print(dic) dic.setdefault('high') # 有key则不修改,无则添加。 dic.setdefault('high', 169) dic.setdefault('name', 'wusir') print(dic)
5.2 删
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
dic = { 'name': '老男孩', 'age': 10000, 'sex': '男', } print(dic.pop('name')) # 返回值 dic.pop('name1',None) print(dic) #popitem 随机删除 有返回值 print(dic.popitem()) print(dic) clear dic.clear() print(dic) del dic print(dic) del dic['name'] print(dic) ''' 1,删除整个字典 2,按照键去删除键值对 '''
5.3 改
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
dic['name'] = 'alex' # 无责增加,有责修改。 print(dic) #update 更新信息 dic = {"name": "jin", "age": 18,"sex": "male"} dic2 = {"name": "alex", "weight": 75} dic2.update(dic) # 将dic里面的键值对覆盖并更新到dic2中,dic不变 。 print(dic) # {'name': 'jin', 'age': 18, 'sex': 'male'} print(dic2) # {'name': 'jin', 'weight': 75, 'age': 18, 'sex': 'male'}
5.4 查
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
print(dic['name']) print(dic['name1']) print(dic.get('name')) print(dic.get('name1','没有此键...')) print(dic.keys()) # 类似于列表的一个容器,没有索引 for i in dic.keys(): print(i) for i in dic: print(i) print(dic.values()) print(dic.items()) for i in dic.items(): print(i)
5.5 字典的嵌套及数据类型的补充
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
dic = {'name_list':['高猛', '于其',], 1:{ 'alex': '李杰', 'high': '175', } } # 1、['高猛', '于其',] 追加一个元素'wusir', # 2, {'alex': '李杰','high': '175' } 增加一个键值对 'sex': man, dic['name_list'].append('wusir') print(dic) print(dic[1]) dic[1]['sex'] = 'man' print(dic) l1 = [11, 22, 33, 44, 55] # 将索引为奇数对应的元素删除。 del l1[1::2] print(l1) #再循环一个列表时,不要改变列表的大小,这样会影响结果。 for i in range(len(l1)): print(i) print(l1) if i % 2 == 1: del l1[i] print(i) print(l1) print(l1) for i in range(len(l1)-1,-1,-1): if i % 2 == 1: del l1[i] print(l1) # dictionary changed size during iteration # 再循环一个字典时,不要改变字典的大小,这样会影响结果。 dic = {'k1': 'v1', 'k2': 'v2', 'k3':'v3', 'name':'alex'} for k in dic: if 'k' in k: dic.pop(k) print(dic) s1 = 'abc' print('a' in s1) l1 = [] for i in dic: if 'k' in i: l1.append(i) print(l1) for i in l1: del dic[i] print(dic) dic = dict.fromkeys('abc',666) print(dic) dic = dict.fromkeys('abc',[]) dic['a'].append(666) print(dic)
6、格式化输出
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# 格式化输出 % 占位符 s d name = input('请输入名字:') age = input('请输入年龄:') job = input('请输入职业:') hobbie = input('请输入爱好:') msg = '''------------ info of %s ----------- Name : %s Age : %d job : %s Hobbie: %s ------------- end ----------------- ''' % (name, name, int(age), job, hobbie) print(msg) >>>输出 请输入名字:bowen 请输入年龄:18 请输入职业:IT 请输入爱好:sleep ------------ info of bowen ----------- Name : bowen Age : 18 job : IT Hobbie: sleep ------------- end ----------------- print('我叫%s,今年%d,学习进度2%%' % ('老男孩', 10000)) #and or not # 1,前后都是比较运算 # 优先级:() > not > and > or print(1 > 2 and 3 < 4 or 4 > 5 and 2 > 1 or 9 < 8) # 2, 前后都是数值 ''' 0 是False 非0 都是True x or y if x is True,return x ''' print(3 or 4) print(1 or 4) print(0 or 4) print(-1 or 4) print(3 and 5) print(3 or 4 and 5) choice = input('>>>').strip() if not choice: pass
7、作业
购物车购物小程序
主要实现功能:
- 要求用户输入自己预期消费额度.
- 展示现有商品信息,要求用户选择
- 用户选择对应商品标号后(注意判断是否超出预期消费额度等操作),保存到购物车
- 用户退出后显示购物车信息以及剩余额度情况
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#!/usr/bin/env python # -*- coding:utf-8 -*- goods = [ ["电脑", 1999], ["鼠标", 400], ["游艇", 1200], ["美女",500] ] #购买的商品重新生成列表 l1 = [] #判断用户的工资是否输入正确 money = input("请输入您的工资:") while not money.isdigit(): money = input("输入有误,请重新输入您的工资:") money = int(money); while True: print("欢迎进入商城".center(50,"*")) print("商品列表".center(50, "-")) print("编号".center(8, " "), "名称".center(28, " "), "价格".center(10, " ")) for i in enumerate(goods): print(str(i[0]).center(10, " "), str(i[1][0]).center(28, " "), str(i[1][1]).center(12, " ")) print("选择完毕请按q键退出并查看选中的商品") user_choose = input("请输入您的选择:") if len(user_choose) == 0: print("您没有选择商品") continue if user_choose.isdigit(): #判断输入的是不是一个数字 user_choose = int(user_choose)#转化成数字 if user_choose >= 0 and user_choose < len(goods):#输入的数字必须小于商品的编号 if (money - goods[user_choose][1]) >= 0: l1.append(goods[user_choose]) #选择的商品加入新的列表 money -= goods[user_choose][1] #扣完商品的价格 print("预算还有%d" % money) else: print("预算不够啦~") else: print("不存在该商品~") elif user_choose == 'q': break else: print("您的输入有误~") print("预算还剩%d了" %(money)) print("已购商品购物车列表信息".center(50, "-")) for i in enumerate(l1): print(str(i[0]).center(10, " "), str(i[1][0]).center(28, " "), str(i[1][1]).center(12, " "))