入门知识拾遗
一、bytes类型
bytes转二进制然后转回来
msg="张杨" print(msg) print(msg.encode("utf-8")) print(msg.encode("utf-8").decode())
二、三元运算
如果条件为真:result = 值1
如果条件为假:result = 值2
三、进制
- 二进制,01
- 八进制,01234567
- 十进制,0123456789
- 十六进制,0123456789ABCDEF 二进制到16进制转换http://jingyan.baidu.com/album/47a29f24292608c0142399cb.html?picindex=1
四、对于Python,一切事物都是对象,对象基于类创建
所以,以下这些值都是对象: "wupeiqi"、38、[‘北京‘, ‘上海‘, ‘深圳‘],并且是根据不同的类生成的对象。
所有字符串或者数字、字典 所具备的方法都存在相对应的类里面,所有对象所具备的功能都保存在相应的类中
布尔值(bool)
真(True)或假(False),0或1
>>> if True: #如果为真 >>> print("ok") #打印OK .... ok
整型(int)
在Python2里,一个int型包含32位,可以存储从-2147483648
到214483647
的整数
一个long型会占用更多的空间,64为可以存储-922372036854775808
到922372036854775808
的整数
python3里long型已经不存在了,而int型可以存储到任意大小的整型,甚至超过64为。
Python内部对整数的处理分为普通整数和长整数,普通整数长度为机器位长,通常都是32位,超过这个范围的整数就自动当长整数处理,而长整数的范围几乎完全没限制,如下:
定义一个整型的变量
# 所定义的变量值不能用单引号或者双引号括起来 >>> age = 18
输出其变量的数据类型
>>> type(age) <type ‘int‘>
整型所具备的方法
bit_length
返回表示该数字的时占用的最少位数
>>> num=20 >>> num.bit_length() 5
conjugate
返回该复数的共轭复数,复数,比如0+2j,其中num.real,num.imag分别返回其实部和虚部,num.conjugate(),返回其共扼复数对象
>>> num=-20 >>> num.conjugate() -20 >>> num=0+2j >>> num.real 0.0 >>> num.imag 2.0 >>> num.conjugate() -2j
字符串(str)
字符串类型是python的序列类型,他的本质就是字符序列,而且python的字符串类型是不可以改变的,你无法将原字符串进行修改,但是可以将字符串的一部分复制到新的字符串中,来达到相同的修改效果。
使用引号创建字符串
创建字符串类型可以使用单引号或者双引号又或者三引号来创建,实例如下
单引号
>>> string= ‘zhangyang‘ #type是查看一个变量的数据类型 >>> type(string) <class ‘str‘>
双引号
>>> string= "zhangyang" >>> type(string) <class ‘str‘>
三引号
>>> string= """zhangyang""" >>> type(string) <class ‘str‘>
字符串所具备的方法
- capitalize(self):
把值得首字母变大写
>>> name="zhangyang"
>>> name.capitalize()
‘Zhangyang‘
- center(self, width, fillchar=None):
内容居中,width:字符串的总宽度;fillchar:填充字符,默认填充字符为空格。
# 定义一个字符串变量,名为"string",内容为"hello word" >>> string="hello word" # 输出这个字符串的长度,用len(value_name) >>> len(string) 10 # 字符串的总宽度为10,填充的字符为"*" >>> string.center(10,"*") ‘hello word‘ # 如果设置字符串的总产都为11,那么减去字符串长度10还剩下一个位置,这个位置就会被*所占用 >>> string.center(11,"*") ‘*hello word‘ # 是从左到右开始填充 >>> string.center(12,"*") ‘*hello word*‘
- count(self, sub, start=None, end=None):
sub
–> 搜索的子字符串start
–> 字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0。end
–> 字符串中结束搜索的位置。字符中第一个字符的索引为 0。默认为字符串的最后一个位置。
用于统计字符串里某个字符出现的次数,可选参数为在字符串搜索的开始与结束位置。
>>> string="hello world" # 默认搜索出来的"l"是出现过两次的 >>> string.count("l") 3 # 如果指定从第三个位置开始搜索,搜索到第六个位置,"l"则出现过一次 >>> string.count("l",3,6)
本节内容:
1. 表、元组操作
2. 字符串操作
3. 字典操作
4. 集合操作
5. 文件操作
6. 字符编码与转码
7. 内置函数
1.表、元组操作
1.查询
names = ["ZhangYang","GuYun","XiangPeng","XuBuSi"]#取zhangyang print(names[0]) #0是从左到右第一个位置#取xiangpengprint(name[2])
a.顾头不顾尾
names = ["ZhangYang","GuYun","XiangPeng","XuBuSi"] print(names[1:3]) #切片["GuYun","XiangPeng"]
b.切片取最后一个
names = ["ZhangYang","GuYun","XiangPeng","XuBuSi"] #下面两个效果一样 print(names[-1]) print(names[3]) print(names[-1:])
c.从右往左中间两位[-x:-x]
names = ["ZhangYang","GuYun","XiangPeng","XuBuSi"] print(names[-3:-1]) print(names[-1:-3])
d.取前几[:x]
names = ["ZhangYang","GuYun","XiangPeng","XuBuSi"] print(names[:2])
e.查找指定数值位置.index()
names = ["ZhangYang","GuYun","XiangPeng","XuBuSi","jerry"] print(names) print(names.index("ZhangYang"))
f.计数.count()
names = ["ZhangYang","GuYun","XiangPeng","XuBuSi","jerry","ZhangYang"] print(names.count("ZhangYang"))
>>> names = ["Alex","Tenglan","Eric","Rain","Tom","Amy"] >>> names[1:4] #取下标1至下标4之间的数字,包括1,不包括4 [‘Tenglan‘, ‘Eric‘, ‘Rain‘] >>> names[1:-1] #取下标1至-1的值,不包括-1 [‘Tenglan‘, ‘Eric‘, ‘Rain‘, ‘Tom‘] >>> names[0:3] [‘Alex‘, ‘Tenglan‘, ‘Eric‘] >>> names[:3] #如果是从头开始取,0可以忽略,跟上句效果一样 [‘Alex‘, ‘Tenglan‘, ‘Eric‘] >>> names[3:] #如果想取最后一个,必须不能写-1,只能这么写 [‘Rain‘, ‘Tom‘, ‘Amy‘] >>> names[3:-1] #这样-1就不会被包含了 [‘Rain‘, ‘Tom‘] >>> names[0::2] #后面的2是代表,每隔一个元素,就取一个 [‘Alex‘, ‘Eric‘, ‘Tom‘] >>> names[::2] #和上句效果一样 [‘Alex‘, ‘Eric‘, ‘Tom‘]
切片取多个元素
>>> names [‘Alex‘, ‘Tenglan‘, ‘Eric‘, ‘Rain‘, ‘Tom‘, ‘Amy‘] >>> names.append("我是新来的") >>> names [‘Alex‘, ‘Tenglan‘, ‘Eric‘, ‘Rain‘, ‘Tom‘, ‘Amy‘, ‘我是新来的‘]
追加
>>> names [‘Alex‘, ‘Tenglan‘, ‘Eric‘, ‘Rain‘, ‘Tom‘, ‘Amy‘, ‘我是新来的‘] >>> names.insert(2,"强行从Eric前面插入") >>> names [‘Alex‘, ‘Tenglan‘, ‘强行从Eric前面插入‘, ‘Eric‘, ‘Rain‘, ‘Tom‘, ‘Amy‘, ‘我是新来的‘] >>> names.insert(5,"从eric后面插入试试新姿势") >>> names [‘Alex‘, ‘Tenglan‘, ‘强行从Eric前面插入‘, ‘Eric‘, ‘Rain‘, ‘从eric后面插入试试新姿势‘, ‘Tom‘, ‘Amy‘, ‘我是新来的‘]
插入
>>> names [‘Alex‘, ‘Tenglan‘, ‘强行从Eric前面插入‘, ‘Eric‘, ‘Rain‘, ‘从eric后面插入试试新姿势‘, ‘Tom‘, ‘Amy‘, ‘我是新来的‘] >>> names[2] = "该换人了" >>> names [‘Alex‘, ‘Tenglan‘, ‘该换人了‘, ‘Eric‘, ‘Rain‘, ‘从eric后面插入试试新姿势‘, ‘Tom‘, ‘Amy‘, ‘我是新来的‘]
修改
>>> del names[2] >>> names [‘Alex‘, ‘Tenglan‘, ‘Eric‘, ‘Rain‘, ‘从eric后面插入试试新姿势‘, ‘Tom‘, ‘Amy‘, ‘我是新来的‘] >>> del names[4] >>> names [‘Alex‘, ‘Tenglan‘, ‘Eric‘, ‘Rain‘, ‘Tom‘, ‘Amy‘, ‘我是新来的‘] >>> >>> names.remove("Eric") #删除指定元素 >>> names [‘Alex‘, ‘Tenglan‘, ‘Rain‘, ‘Tom‘, ‘Amy‘, ‘我是新来的‘] >>> names.pop() #删除列表最后一个值 ‘我是新来的‘ >>> names [‘Alex‘, ‘Tenglan‘, ‘Rain‘, ‘Tom‘, ‘Amy‘]
删除
>>> names [‘Alex‘, ‘Tenglan‘, ‘Rain‘, ‘Tom‘, ‘Amy‘] >>> b = [1,2,3] >>> names.extend(b) >>> names [‘Alex‘, ‘Tenglan‘, ‘Rain‘, ‘Tom‘, ‘Amy‘, 1, 2, 3]
拓展
>>> names [‘Alex‘, ‘Tenglan‘, ‘Rain‘, ‘Tom‘, ‘Amy‘] >>> b = [1,2,3] >>> names.extend(b) >>> names [‘Alex‘, ‘Tenglan‘, ‘Rain‘, ‘Tom‘, ‘Amy‘, 1, 2, 3]
拷贝
>>> names [‘Alex‘, ‘Tenglan‘, ‘Amy‘, ‘Tom‘, ‘Amy‘, 1, 2, 3] >>> names.count("Amy") 2
统计
>>> names [‘Alex‘, ‘Tenglan‘, ‘Amy‘, ‘Tom‘, ‘Amy‘, 1, 2, 3] >>> names.sort() #排序 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unorderable types: int() < str() #3.0里不同数据类型不能放在一起排序了,擦 >>> names[-3] = ‘1‘ >>> names[-2] = ‘2‘ >>> names[-1] = ‘3‘ >>> names [‘Alex‘, ‘Amy‘, ‘Amy‘, ‘Tenglan‘, ‘Tom‘, ‘1‘, ‘2‘, ‘3‘] >>> names.sort() >>> names [‘1‘, ‘2‘, ‘3‘, ‘Alex‘, ‘Amy‘, ‘Amy‘, ‘Tenglan‘, ‘Tom‘] >>> names.reverse() #反转 >>> names [‘Tom‘, ‘Tenglan‘, ‘Amy‘, ‘Amy‘, ‘Alex‘, ‘3‘, ‘2‘, ‘1‘]
排序&翻转
>>> names [‘Tom‘, ‘Tenglan‘, ‘Amy‘, ‘Amy‘, ‘Alex‘, ‘3‘, ‘2‘, ‘1‘] >>> names.index("Amy") 2 #只返回找到的第一个下标
获取下标
获取下标
2.增加 append
a.增加到最后面
names = ["ZhangYang","GuYun","XiangPeng","XuBuSi"] names.append("leihaidong")
b.指定位置插入 insert
names = ["ZhangYang","GuYun","XiangPeng","XuBuSi"] names.append("LeiHaDong") names.insert(1,"jerry") print(names)
3.更改
a.指定位置替换,
names = ["ZhangYang","GuYun","XiangPeng","XuBuSi"] names.append("LeiHaDong") names.insert(1,"jerry") names[2]="xiedi" #指定位置替换值 print(names)
4.删除
names = ["ZhangYang","GuYun","XiangPeng","XuBuSi","jerry"] #del names.remove("jerry") #方法一 del names[3] #方法二 names.pop() #删掉最后一个
其他参数:
清空.clear()
names.clear
列表反转.reverse()
names = ["ZhangYang","GuYun","XiangPeng","XuBuSi","jerry"] names.reverse() print(names)
排序.sort()
names = ["ZhangYang","GuYun","XiangPeng","XuBuSi","Jerry"] names.sort() print(names)#排序规则:特殊字符 数字 大写 小写
合并extend()
names = ["ZhangYang","GuYun","XiangPeng","XuBuSi","Jerry"] print(names) names2 =[1,2,3,4] names.extend(names2) print(names)
复制copy()
names = ["ZhangYang","GuYun","XiangPeng","XuBuSi","Jerry"] names2=names.copy() print(names) print(names2)
浅copy--copy一层
names = ["ZhangYang","GuYun","XiangPeng",["alex","jack"],"XuBuSi","Jerry"] names2=names.copy() print(names) print(names2) names[2] = "向鹏" names[3] [0]="ALEXANDER" print(names) print(names2)
深copy--完全
# -*- conding:utf-8 -*- #Author:YoungCheung import copy names = ["ZhangYang","GuYun","XiangPeng",["alex","jack"],"XuBuSi","Jerry"] names2=copy.deepcopy(names) # names2=names.copy() print(names) print(names2) names[2] = "向鹏" names[3] [0]="ALEXANDER" print(names) print(names2)
列表循环
# -*- conding:utf-8 -*- #Author:YoungCheung names = ["ZhangYang","GuYun","XiangPeng",["alex","jack"],"XuBuSi","Jerry"] for i in names: print(i)
不常切片
# -*- conding:utf-8 -*- #Author:YoungCheung names = ["ZhangYang","GuYun","XiangPeng",["alex","jack"],"XuBuSi","Jerry"] print(names[0:-1:2]) print(names[::2])
程序练习
请闭眼写出以下程序。
程序:购物车程序
需求:
- 启动程序后,让用户输入工资,然后打印商品列表
- 允许用户根据商品编号购买商品
- 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
- 可随时退出,退出时,打印已购买商品和余额
# -*- conding:utf-8 -*- #Author:YoungCheung product_list=[ (‘Iphone‘,5800), (‘Mac pro‘,9800), (‘Bike‘,800), (‘Watch‘,10600), (‘cofee‘,31), (‘alex python‘,120), ] shoping_list=[] salary=input("please input your salary:") if salary.isdigit(): salary=int(salary) while True: # for item inproduct_list: for index,item in enumerate(product_list): print(index,item) # print(product_list.index(item),item) user_choice=input("选择您想买商品>>>:") if user_choice.isdigit(): user_choice=int(user_choice) if user_choice<len(product_list) and user_choice>=0: product_item = product_list[user_choice] if product_item [1] <= salary: #买得起 shoping_list.append( product_item ) salary -= product_item [1] print("added %s into shoping cart,your current balance is \033[31;1m%s\033[0m" %( product_item ,salary)) else: print("\033[41;1m你的余额只剩下[%s]啦,买不了啦\033[0m") else: print("product code [%s] is not exist!" % user_choice) elif user_choice ==‘quit‘: print(‘------shoping list----------------‘) for p in shoping_list: print(p) print("your current balance:",salary) exit() else: print("invalid option")
购物车
2.字符串操作
>>> n3_arg {‘name‘: ‘alex‘, ‘age‘: 33} >>> n3 ‘my name is {name} and age is {age}‘ >>> n3.format_map(n3_arg) ‘my name is alex and age is 33‘ >>> n4.ljust(40,"-") ‘Hello 2orld-----------------------------‘ >>> n4.rjust(40,"-") ‘-----------------------------Hello 2orld‘ >>> s = "Hello World!" >>> p = str.maketrans("abcdefg","[email protected]#$%^") >>> s.translate(p) ‘H$llo Worl#! >>> b="ddefdsdff_哈哈" >>> b.isidentifier() #检测一段字符串可否被当作标志符,即是否符合变量命名规则 True 一些蛋疼的语法
蛋疼的字符串操作
3.字典操作
字典一种key - value 的数据类型,使用就像我们上学用的字典,通过笔划、字母来查对应页的详细内容。
语法:
info = { ‘stu1101‘: "TengLan Wu", ‘stu1102‘: "LongZe Luola", ‘stu1103‘: "XiaoZe Maliya", }
字典的特性:
- dict是无序的
- key必须是唯一的,so 天生去重
>>> info["stu1104"] = "苍井空" >>> info {‘stu1102‘: ‘LongZe Luola‘, ‘stu1104‘: ‘苍井空‘, ‘stu1103‘: ‘XiaoZe Maliya‘, ‘stu1101‘: ‘TengLan Wu‘}
增加
>>> info[‘stu1101‘] = "武藤兰" >>> info {‘stu1102‘: ‘LongZe Luola‘, ‘stu1103‘: ‘XiaoZe Maliya‘, ‘stu1101‘: ‘武藤兰‘}
修改
>>> info {‘stu1102‘: ‘LongZe Luola‘, ‘stu1103‘: ‘XiaoZe Maliya‘, ‘stu1101‘: ‘武藤兰‘} >>> info.pop("stu1101") #标准删除姿势 ‘武藤兰‘ >>> info {‘stu1102‘: ‘LongZe Luola‘, ‘stu1103‘: ‘XiaoZe Maliya‘} >>> del info[‘stu1103‘] #换个姿势删除 >>> info {‘stu1102‘: ‘LongZe Luola‘} >>> >>> >>> >>> info = {‘stu1102‘: ‘LongZe Luola‘, ‘stu1103‘: ‘XiaoZe Maliya‘} >>> info {‘stu1102‘: ‘LongZe Luola‘, ‘stu1103‘: ‘XiaoZe Maliya‘} #随机删除 >>> info.popitem() (‘stu1102‘, ‘LongZe Luola‘) >>> info {‘stu1103‘: ‘XiaoZe Maliya‘}
删除
>>> info = {‘stu1102‘: ‘LongZe Luola‘, ‘stu1103‘: ‘XiaoZe Maliya‘} >>> >>> "stu1102" in info #标准用法 True >>> info.get("stu1102") #获取 ‘LongZe Luola‘ >>> info["stu1102"] #同上,但是看下面 ‘LongZe Luola‘ >>> info["stu1105"] #如果一个key不存在,就报错,get不会,不存在只返回None Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: ‘stu1105‘
查找
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"]) #ouput [‘全部免费,真好,好人一生平安‘, ‘服务器在国外,慢,可以用爬虫爬下来‘]
多级字典嵌套及操作
#values >>> info.values() dict_values([‘LongZe Luola‘, ‘XiaoZe Maliya‘]) #keys >>> info.keys() dict_keys([‘stu1102‘, ‘stu1103‘]) #setdefault >>> info.setdefault("stu1106","Alex") ‘Alex‘ >>> info {‘stu1102‘: ‘LongZe Luola‘, ‘stu1103‘: ‘XiaoZe Maliya‘, ‘stu1106‘: ‘Alex‘} >>> info.setdefault("stu1102","龙泽萝拉") ‘LongZe Luola‘ >>> info {‘stu1102‘: ‘LongZe Luola‘, ‘stu1103‘: ‘XiaoZe Maliya‘, ‘stu1106‘: ‘Alex‘} #update >>> info {‘stu1102‘: ‘LongZe Luola‘, ‘stu1103‘: ‘XiaoZe Maliya‘, ‘stu1106‘: ‘Alex‘} >>> b = {1:2,3:4, "stu1102":"龙泽萝拉"} >>> info.update(b) >>> info {‘stu1102‘: ‘龙泽萝拉‘, 1: 2, 3: 4, ‘stu1103‘: ‘XiaoZe Maliya‘, ‘stu1106‘: ‘Alex‘} #items info.items() dict_items([(‘stu1102‘, ‘龙泽萝拉‘), (1, 2), (3, 4), (‘stu1103‘, ‘XiaoZe Maliya‘), (‘stu1106‘, ‘Alex‘)]) #通过一个列表生成默认dict,有个没办法解释的坑,少用吧这个 >>> dict.fromkeys([1,2,3],‘testd‘) {1: ‘testd‘, 2: ‘testd‘, 3: ‘testd‘}
换个姿势
#方法1 for key in info: print(key,info[key]) #方法2 for k,v in info.items(): #会先把dict转成list,数据里大时莫用 print(k,v)
循环dictionary
程序练习
程序: 三级菜单
要求:
- 打印省、市、县三级菜单
- 可返回上一级
- 可随时退出程序
# -*- conding:utf-8 -*- #Author:YoungCheung menu ={ "北京市":{ "东城区":["东华门街道","景山街道","交道口街道","安定门街道","北新桥街道","朝阳门街道","东四街道","建国门街道","东直门街道","前门街道","崇文门外街道","东花市街道","龙潭街道","体育馆路街道","天坛街道","永定门外街"], "西城区":["西长安街街道"," 新街口街道","月坛街道","展览路街道","德胜街道","金融街街道","什刹海街道","大栅栏街道","天桥街道","椿树街道","陶然亭街道","广内街道","牛街街道","白纸坊街道","广外街道"], "朝阳区":["建外街道","朝外街道","呼家楼街道","三里屯街道","左家庄街道","香河园街道","和平街街道","安贞街道","亚运村街道","小关街道","酒仙桥街道","麦子店街道","团结湖街道","六里屯街道"], "丰台区":["右安门街道","太平桥街道","西罗园街道","大红门街道","南苑街道","东高地街道","东铁匠营街道","卢沟桥街道","丰台街道","新村街道","长辛店街道","云岗街道","方庄地区","宛平城地区","马家堡街道","和义街道","卢沟桥地区","花乡地区","南苑地区","长辛店镇","王佐镇"], "通州区":["中仓街道","新华街道","北苑街道","玉桥街道","永顺街道","梨园街道","宋庄镇","张家湾镇","漷县镇","马驹桥镇","西集镇","台湖镇","永乐店镇","潞城镇","于家务回族乡"], "石景山区":["八宝山街道","老山街道","八角街道","古城街道","苹果园街道","金顶街街道","广宁街道","五里坨街道","鲁谷街道"], "海淀区":["万寿路街道","永定路街道","羊坊店街道","甘家口街道","八里庄街道","紫竹院街道","北下关街道","北太平庄街道","学院路街道","中关村街道","海淀街道","青龙桥街道","清华园街道","燕园街道","香山街道","清河街道","花园路街道","西三旗街道","马连洼街道","田村路街道","上地街道","万柳地区","东升地区","曙光街道","温泉镇","四季青镇","西北旺镇","苏家坨镇","上庄镇"], "房山区":["城关街道","新镇街道","向阳街道","东风街道","迎风街道","星城街道","良乡地区","周口店地区","琉璃河地区","拱辰街道","西潞街道","阎村镇","窦店镇","石楼镇","长阳镇","河北镇","长沟镇","大石窝镇","张坊镇","十渡镇","青龙湖镇","韩村河镇","霞云岭乡","南窖乡","佛子庄乡","大安山乡","史家营乡","蒲洼乡"], "门头沟区":["大峪街道","城子街道","东辛房街道","大台街道","王平街道","潭柘寺镇","永定镇","龙泉镇","军庄镇","雁翅镇","斋堂镇","清水镇","妙峰山镇"], "大兴区":["兴丰街道","林校路街道","清源街道","亦庄地区","黄村地区","旧宫地区","西红门镇","瀛海地区","观音寺街道","天宫院街道","青云店镇","采育镇","安定镇","礼贤镇","榆垡镇","庞各庄镇","北臧村镇","魏善庄镇","长子营镇"], "怀柔区":["怀柔地区","泉河街道","龙山街道","雁栖地区","庙城地区","北房镇","杨宋镇","桥梓镇","怀北镇","汤河口镇","渤海镇","九渡河镇","琉璃庙镇","宝山镇","长哨营满族乡","喇叭沟门满族乡"], "平谷区":["滨河街道","兴谷街道","渔阳地区","峪口镇","马坊地区","金海湖地区","东高村镇","山东庄镇","南独乐河镇","大华山镇","夏各庄镇","马昌营镇","王辛庄镇","大兴庄镇","刘家店镇","镇罗营镇","黄松峪乡","熊儿寨乡"], "密云区":["鼓楼街道","果园街道","檀营地区","密云镇","溪翁庄镇","西田各庄镇","十里堡镇","河南寨镇","巨各庄镇","穆家峪镇","太师屯镇","高岭镇","不老屯镇","冯家峪镇","古北口镇","大城子镇","东邵渠镇","北庄镇","新城子镇","石城镇"], "延庆区":["百泉街道","香水园街道","儒林街道","延庆镇","康庄镇","八达岭镇","永宁镇","旧县镇","张山营镇","四海镇","千家店镇","沈家营镇","大榆树镇","井庄镇","大庄科乡","刘斌堡乡","香营乡","珍珠泉乡"], "顺义区":["胜利街道","光明街道","仁和街道","后沙峪街道","天竺街道","杨镇街道","牛栏山街道","南法信街道","马坡街道","石园街道","空港街道","双丰街道","旺泉街道","高丽营镇","李桥镇","李遂镇","南彩镇","北务镇","大孙各庄镇","张镇","龙湾屯镇","木林镇","北小营镇","北石槽镇","赵全营镇"], }, } print ("++++++++++++++++北京地图查询系统+++++++++++++++++") for i in menu: print (i) jump_flag = False #用于跳出外循环 for i in range(3): #外循环,指定循环3次,3次外循环完了,就退出程序 city_name = input("请输入你要查看的市:") if city_name in menu: exist_name = menu[city_name] district_name = exist_name.keys()#使用输入的信息作为key,取出区信息,存在字典中 while True: #内循环,死循环,不指定循环次数,通过break或者flag跳出 for i in district_name: #遍历列表,取出区名字,打印出来 print (i) town_name_input = input("请输入你要查看的区:") if town_name_input in district_name: #判断输入的省名字是否在地区列表中 z_name = menu[city_name][town_name_input] #取出区中有哪些镇,存在列表中 for i in z_name: #遍历列表,取出镇名字,打印出来 print (i) if town_name_input not in district_name: #如果输入的区名字不在在地区列表中 print ("输入的区名字不对,请重新输入") continue #跳出当次迭代,开始下一次迭代循环,直到名字输入正确为止(不停的要求输入) back_or_quit = input("请问是否退出?" "Back是返回上一级菜单;" "Exit是退出整个程序") if back_or_quit == "quit": jump_flag = True #用于跳出外循环 break #跳出while内循环 if back_or_quit == "back": continue # 跳出当次迭代,开始下一次迭代循环,重新输入,返回上一步 print ("你输入的信息有误,请重新输入:") if jump_flag: #跳出外循环的条件满足 break #跳出外循环 else:#上面的3次for循环正常执行完毕,else才会执行,如果是不正常退出(break),else不会执行 print ("3次输入错误,程序退出...........")
三级菜单
4.集合操作
集合是一个无序的,不重复的数据组合,它的主要作用如下:
- 去重,把一个列表变成集合,就自动去重了
- 关系测试,测试两组数据之前的交集、差集、并集等关系
常用操作
s = set([3,5,9,10]) #创建一个数值集合 t = set("Hello") #创建一个唯一字符的集合 a = t | s # t 和 s的并集 b = t & s # t 和 s的交集 c = t – s # 求差集(项在t中,但不在s中) d = t ^ s # 对称差集(项在t或s中,但不会同时出现在二者中) 基本操作: t.add(‘x‘) # 添加一项 s.update([10,37,42]) # 在s中添加多项 使用remove()可以删除一项: t.remove(‘H‘) len(s) set 的长度 x in s 测试 x 是否是 s 的成员 x not in s 测试 x 是否不是 s 的成员 s.issubset(t) s <= t 测试是否 s 中的每一个元素都在 t 中 s.issuperset(t) s >= t 测试是否 t 中的每一个元素都在 s 中 s.union(t) s | t 返回一个新的 set 包含 s 和 t 中的每一个元素 s.intersection(t) s & t 返回一个新的 set 包含 s 和 t 中的公共元素 s.difference(t) s - t 返回一个新的 set 包含 s 中有但是 t 中没有的元素 s.symmetric_difference(t) s ^ t 返回一个新的 set 包含 s 和 t 中不重复的元素 s.copy() 返回 set “s”的一个浅复制
常用操作
5. 文件操作
对文件操作流程
- 打开文件,得到文件句柄并赋值给一个变量
- 通过句柄对文件进行操作
- 关闭文件
现有文件如下
Somehow, it seems the love I knew was always the most destructive kind 不知为何,我经历的爱情总是最具毁灭性的的那种 Yesterday when I was young 昨日当我年少轻狂 The taste of life was sweet 生命的滋味是甜的 As rain upon my tongue 就如舌尖上的雨露 I teased at life as if it were a foolish game 我戏弄生命 视其为愚蠢的游戏 The way the evening breeze 就如夜晚的微风 May tease the candle flame 逗弄蜡烛的火苗 The thousand dreams I dreamed 我曾千万次梦见 The splendid things I planned 那些我计划的绚丽蓝图 I always built to last on weak and shifting sand 但我总是将之建筑在易逝的流沙上 I lived by night and shunned the naked light of day 我夜夜笙歌 逃避白昼赤裸的阳光 And only now I see how the time ran away 事到如今我才看清岁月是如何匆匆流逝 Yesterday when I was young 昨日当我年少轻狂 So many lovely songs were waiting to be sung 有那么多甜美的曲儿等我歌唱 So many wild pleasures lay in store for me 有那么多肆意的快乐等我享受 And so much pain my eyes refused to see 还有那么多痛苦 我的双眼却视而不见 I ran so fast that time and youth at last ran out 我飞快地奔走 最终时光与青春消逝殆尽 I never stopped to think what life was all about 我从未停下脚步去思考生命的意义 And every conversation that I can now recall 如今回想起的所有对话 Concerned itself with me and nothing else at all 除了和我相关的 什么都记不得了 The game of love I played with arrogance and pride 我用自负和傲慢玩着爱情的游戏 And every flame I lit too quickly, quickly died 所有我点燃的火焰都熄灭得太快 The friends I made all somehow seemed to slip away 所有我交的朋友似乎都不知不觉地离开了 And only now I‘m left alone to end the play, yeah 只剩我一个人在台上来结束这场闹剧 Oh, yesterday when I was young 噢 昨日当我年少轻狂 So many, many songs were waiting to be sung 有那么那么多甜美的曲儿等我歌唱 So many wild pleasures lay in store for me 有那么多肆意的快乐等我享受 And so much pain my eyes refused to see 还有那么多痛苦 我的双眼却视而不见 There are so many songs in me that won‘t be sung 我有太多歌曲永远不会被唱起 I feel the bitter taste of tears upon my tongue 我尝到了舌尖泪水的苦涩滋味 The time has come for me to pay for yesterday 终于到了付出代价的时间 为了昨日 When I was young 当我年少轻狂
基本操作
f = open(‘lyrics‘) #打开文件 first_line = f.readline() print(‘first line:‘,first_line) #读一行 print(‘我是分隔线‘.center(50,‘-‘)) data = f.read()# 读取剩下的所有内容,文件大时不要用 print(data) #打印文件 f.close() #关闭文件
打开文件的模式有:
- r,只读模式(默认)。
- w,只写模式。【不可读;不存在则创建;存在则删除内容;】
- a,追加模式。【可读; 不存在则创建;存在则只追加内容;】
"+" 表示可以同时读写某个文件
- r+,可读写文件。【可读;可写;可追加】
- w+,写读
- a+,同a
"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)
- rU
- r+U
"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)
- rb
- wb
- ab
def close(self): # real signature unknown; restored from __doc__ """ Close the file. A closed file cannot be used for further I/O operations. close() may be called more than once without error. """ pass def fileno(self, *args, **kwargs): # real signature unknown """ Return the underlying file descriptor (an integer). """ pass def isatty(self, *args, **kwargs): # real signature unknown """ True if the file is connected to a TTY device. """ pass def read(self, size=-1): # known case of _io.FileIO.read """ 注意,不一定能全读回来 Read at most size bytes, returned as bytes. Only makes one system call, so less data may be returned than requested. In non-blocking mode, returns None if no data is available. Return an empty bytes object at EOF. """ return "" def readable(self, *args, **kwargs): # real signature unknown """ True if file was opened in a read mode. """ pass def readall(self, *args, **kwargs): # real signature unknown """ Read all data from the file, returned as bytes. In non-blocking mode, returns as much as is immediately available, or None if no data is available. Return an empty bytes object at EOF. """ pass def readinto(self): # real signature unknown; restored from __doc__ """ Same as RawIOBase.readinto(). """ pass #不要用,没人知道它是干嘛用的 def seek(self, *args, **kwargs): # real signature unknown """ Move to new file position and return the file position. Argument offset is a byte count. Optional argument whence defaults to SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values are SEEK_CUR or 1 (move relative to current position, positive or negative), and SEEK_END or 2 (move relative to end of file, usually negative, although many platforms allow seeking beyond the end of a file). Note that not all file objects are seekable. """ pass def seekable(self, *args, **kwargs): # real signature unknown """ True if file supports random-access. """ pass def tell(self, *args, **kwargs): # real signature unknown """ Current file position. Can raise OSError for non seekable files. """ pass def truncate(self, *args, **kwargs): # real signature unknown """ Truncate the file to at most size bytes and return the truncated size. Size defaults to the current file position, as returned by tell(). The current file position is changed to the value of size. """ pass def writable(self, *args, **kwargs): # real signature unknown """ True if file was opened in a write mode. """ pass def write(self, *args, **kwargs): # real signature unknown """ Write bytes b to file, return number written. Only makes one system call, so not all of the data may be written. The number of bytes actually written is returned. In non-blocking mode, returns None if the write would block. """ pass
其他语法
with语句
为了避免打开文件后忘记关闭,可以通过管理上下文,即:
with open(‘log‘,‘r‘) as f: ...
如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。
在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:
with open(‘log1‘) as obj1, open(‘log2‘) as obj2: pass
程序练习
程序1: 实现简单的shell sed替换功能
程序2:修改haproxy配置文件
1、查 输入:www.oldboy.org 获取当前backend下的所有记录 2、新建 输入: arg = { ‘bakend‘: ‘www.oldboy.org‘, ‘record‘:{ ‘server‘: ‘100.1.7.9‘, ‘weight‘: 20, ‘maxconn‘: 30 } } 3、删除 输入: arg = { ‘bakend‘: ‘www.oldboy.org‘, ‘record‘:{ ‘server‘: ‘100.1.7.9‘, ‘weight‘: 20, ‘maxconn‘: 30 } } 需求
需求
global log 127.0.0.1 local2 daemon maxconn 256 log 127.0.0.1 local2 info defaults log global mode http timeout connect 5000ms timeout client 50000ms timeout server 50000ms option dontlognull listen stats :8888 stats enable stats uri /admin stats auth admin:1234 frontend oldboy.org bind 0.0.0.0:80 option httplog option httpclose option forwardfor log global acl www hdr_reg(host) -i www.oldboy.org use_backend www.oldboy.org if www backend www.oldboy.org server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000
原配置文件
6. 字符编码与转码
#-*-coding:utf-8-*- __author__ = ‘Alex Li‘ import sys print(sys.getdefaultencoding()) msg = "我爱北京天安门" msg_gb2312 = msg.decode("utf-8").encode("gb2312") gb2312_to_gbk = msg_gb2312.decode("gbk").encode("gbk") print(msg) print(msg_gb2312) print(gb2312_to_gbk) in python2
In Python2
#-*-coding:gb2312 -*- #这个也可以去掉 __author__ = ‘Alex Li‘ import sys print(sys.getdefaultencoding()) msg = "我爱北京天安门" #msg_gb2312 = msg.decode("utf-8").encode("gb2312") msg_gb2312 = msg.encode("gb2312") #默认就是unicode,不用再decode,喜大普奔 gb2312_to_unicode = msg_gb2312.decode("gb2312") gb2312_to_utf8 = msg_gb2312.decode("gb2312").encode("utf-8") print(msg) print(msg_gb2312) print(gb2312_to_unicode) print(gb2312_to_utf8)
In Python3
.