模块初识
Python中模块又简称为“库”,库分为两种,一种为标准库,一种为第三方库。
标准库:不需要安装,可以直接导入,可以使用python的最常用功能。eg:getpass、os、sys
第三方库:必须要安装才能使用。eg:django 这个库必须安装才能用使用.
OS模块
1 >>> import os
2 >>> os.system('pwd')
3 /Users/sean/python/s14/zuoye/day2
os模块 V1
import os
res = os.system('dir')
print('--->',res)
---------------------------
C:\>Python os.py
驱动器 C 中的卷没有标签。
卷的序列号是 7453-A691
C:\ 的目录
16/07/23 下午03:21 22 hello.py
16/08/02 下午01:30 52 os.py
09/07/14 上午11:20 <DIR> PerfLogs
11/04/12 下午10:57 <DIR> Program Files
16/07/29 下午06:20 <DIR> Program Files (x86)
16/07/20 下午12:02 <DIR> Python27
16/07/21 上午02:07 <DIR> Users
16/07/20 下午12:00 <DIR> Windows
2 个文件 74 字节
6 个目录 118,389,239,808 可用字节
---> 0 #这里打印的为什么是个零呢? 而不是一个真正的dir的数据呢?这里要说一下了,system方法就是这样的,他只返回数据的执行结果是正确执行,还是错误执行,这里的0就表示命令执行成功,只要是非零就表示上面的命令执行失败。那有人该问了,我就想要命令的执行结果,不想要命令的执行状态,别急继续往下看。
os模块V2
import os
res = os.popen('dir') #这里是用os的popen方法就会有你想要的了
print('--->',res)
看一下执行结果:
C:\>Python os.py
---> <os._wrap_close object at 0x002EF450> #what the fack! 这是打印的啥玩意,其实这是打印的返回数据的内存存放地址,如果想调出这个地址,还需要有如下一步
os模块V3
import os
res = os.popen('dir').read()
print('--->',res)
看一下执行结果:
#oh,yes!就是这个结果。
C:\>Python os.py
---> 驱动器 C 中的卷没有标签。
卷的序列号是 7453-A691
C:\ 的目录
16/07/23 下午03:21 22 hello.py
16/08/02 下午01:37 58 os.py
09/07/14 上午11:20 <DIR> PerfLogs
11/04/12 下午10:57 <DIR> Program Files
16/07/29 下午06:20 <DIR> Program Files (x86)
16/07/20 下午12:02 <DIR> Python27
16/07/21 上午02:07 <DIR> Users
16/07/20 下午12:00 <DIR> Windows
2 个文件 80 字节
6 个目录 118,386,798,592 可用字节
##注意##
上面的这种方法,在linux下我测试有问题,打印出来没有格式化输出。
os模块V4
这里再说一下os的另外两个方法,os.mkdir和os.mkdirs,前者是创建一个目录,后者是创建多级目录。可以尝试使用下!
sys模块
#!/usr/bin/env python
import sys
print (sys.argv)
print (sys.argv[0])
print (sys.argv[1])
res = sys.argv
print(res)
bogon:day2 sean$ python import_os_argv.py start stop
['import_os_argv.py', 'start', 'stop']
import_os_argv.py
start
['import_os_argv.py', 'start', 'stop']
可以看到sys.argv这个方法返回的是一个列表,如果想取出某个值,使用列表方法就能取到,关于列表的知识我们后面会继续讲。
上面都是标准库,我接下来也不会说第三方库,因为我也不会用;那我们自己就写一个简单的库,然后调用这个库,在说这个之前我们先说一下环境变量的事情。
我们调用一下sys模块,执行一下sys.path这个方法,看一下返回的数据。
>>> import sys
>>> sys.path
['', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python35.zip', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/plat-darwin', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages']
我们能看到是一个列表的数据,其中有很多的路径元素,讲讲这些元素有什么用。
这个列表的整体作用是用在当用户执行导入一个模块的动作的情况下,python解释器会到这些相应的路径下寻找你的模块,如果找到那么顺利引用,如果没找到,
那么肯定报错喽!当然如果你引入模块写的绝对路径,他就不会使用这个参数进行模块导入了,第一个有的人会问了怎么是一个空路径,其实这个表示是在当前
目录查找的意思。下面我们来自己写一个模块尝试导入试试:
自己写个非常low的模块导入试试看:
1 bogon:day2 sean$ ls -l #查看一下当前目录下的文件
2 total 16
3 -rw-r--r-- 1 sean staff 42 8 2 11:27 import_os_argv.py
4 -rw-r--r-- 1 sean staff 47 8 2 11:26 print_module.py
5 bogon:day2 sean$ cat import_os_argv.py #查看一下执行文件
6 #!/usr/bin/env python
7 import print_module
8 bogon:day2 sean$ cat print_module.py #查看一下我写的简单模块内容
9 print('This is an example of a module import')
10 bogon:day2 sean$
11 #当我引用这个模块的时候,模块的打印内容便输出到命令行了。
12 bogon:day2 sean$ python import_os_argv.py
13 This is an example of a module import
三元运算符
>>> a,b,c = 3,6,9
#这句话的意思是,如果 a>b 那么d就等于a,否则d就等于c
>>> d = a if a > b else c
>>> print(d)
9
>>>
>>> a,b,c = 3,6,9
#如果c>b那么d就等于a,否则d就等于c
>>> d = a if c > b else c
>>> print(d)
3
>>>
如果不使用这种方法,那么就的老老实实的写if...else ...了,是不是有点麻烦。
进制
二进制:01
八进制:01234567
十进制:0123456789
十六进制:0123456789ABCDEF
我们来做一下二进制与十六进制之间的转换:
我们把16进制的 BF873转化为二进制,首先我们要清楚二进制和十六进制之间的对照关系,如下:
0 1 2 3 4 5 6 7 8 9 A B C D E F
0000 0001 0010 0011 0100 0101 0111 0111 1000 1001 1010 1011 1100 1101 1110 1111
那么这个十六进制的BF873是怎么转化成二进制呢?我们来讲一下规则,首先把每个数字都按照1拆4的规则进行拆分,如下:
B F 8 7 3
1011 1111 1000 0111 0011
那么最后的二进制为10111111100001110011 = BF873
需要补充的就是,如果有小数点的,小数点两边不能凑齐8位或者被8整除的位数,那么可以补零来进行换算,我们下面来换算一个2进制转换成16进制的例子
10101111001010.1011001
首先先看一下小数点左右是否可以被4整除,如果不能那么就用零来补充
0010 1011 1100 1010 . 1011 0010
2 B C A . B 2
那么最后的16进制就是2BCA.B2
bytes数据类型
在python2.0版本中,是不区分bytes类型和str类型的,二者存在隐转换的,所谓的隐式举个例子,在python2中如果用的数字大了,自动给你转成log了,但是在python3中不会这样了,要么报错,要么你手动的转换。所以说在python3.0里面二者是存在严格的区分的,也就是说你不能手动拼接字符串和数据包,也不能在
字节包里面搜索字符串(反之亦然)。
在python3中所有的字符串默认是Unicode编码,转换成任何编码只需要直接解码就好了。下面的图一定要牢记:
在python中二进制的数据都是bytes的数据类型,文本都是字符串的数据类型,
>>> msg = '我爱北京天安门'
>>> print(msg)
我爱北京天安门>>> print (msg.encode('utf-8'))
b'\xe6\x88\x91\xe7\x88\xb1\xe5\x8c\x97\xe4\xba\xac\xe5\xa4\xa9\xe5\xae\x89\xe9\x
97\xa8'
>>> b'\xe6\x88\x91\xe7\x88\xb1\xe5\x8c\x97\xe4\xba\xac\xe5\xa4\xa9\xe5\xae\x89\x
e9\x97\xa8'.decode('utf-8')
'我爱北京天安门'
>>>
列表
1.创建一个列表并默认输出所有列表元素
>>> name_list = ['sean','tom','jack','Angelia','Daisy','jack']
>>> print(name_list)
['sean', 'tom', 'jack', 'Angelia', 'Daisy', 'jack']
>>>
2.调出列表中的地2个元素‘tom’
#这里输入的1是表示tom所在列表中的下标
>>> print(name_list[1])
tom
我们可以查看一下tom的下标是不是为1,
>>> name_list.index('tom')
1
我们想为什么是1而不是2呢?这是因为计算机是从0开始计数的,第一个的下标也就是0了
3.列表的切片,我想取出列表的第二个到第五个的数据,也就是'tom','jack','Angelia','Daisy'这几个数据
#这里为什么是1:5而不是1:4呢?这里列表有一个原则学名叫做“左闭又开”,大白话就叫做“顾头不顾尾”,大概意思就是切片会吧开始的切上,结尾不会给切上的。
>>> print(name_list[1:5])
['tom', 'jack', 'Angelia', 'Daisy']
#如果开头不写的话,默认就是从第一个元素开始取,也就是从下标为0的元素开始往外取
>>> print(name_list[:5])
['tom', 'jack', 'Angelia', 'Daisy']
4.元素少的情况下,我们能知道最后一个元素是多少,所以可以直接拿到,但是当一个列表有2W+个元素的时候,甚至更多,我们该如何调取最后一个元素呢?
#这里的-1默认就是最后一个
>>> print(name_list[-1])
jack
那我们如果想取出倒数第一个到倒数第三个呢? 我们就要这么写了
#由于切片是左闭右开的原则,所以如果写成-3:-1那么最后一个元素将不被切出了。所以我们直接省略了-1
>>> print(name_list[-3:])
['Angelia', 'Daisy', 'jack']
5.增加用户
第一种方法是直接追加到列表的最后位置
>>> name_list
['sean', 'tom', 'jack', 'Angelia', 'Daisy', 'jack']
>>> name_list.append('sary')
>>> name_list
['sean', 'tom', 'jack', 'Angelia', 'Daisy', 'jack', 'sary']
第二种方法是插入到指定位置,如果我想加一个用户为alex,把alex插到tom前面
#1的意思是插入到这个列表的什么位置,我们想插入到tom的前面,那插入后的下标是1,所以这里就写1
>>> name_list.insert(1,'alex')
>>> name_list
['sean', 'alex', 'tom', 'jack', 'Angelia', 'Daisy', 'jack', 'sary']
6.更改用户,现在把alex改为dave
#首先我们要先获取到alex这个名字的下标位置
>>> name_list.index('alex')
1
#然后把下标位置为1的名字改为dave
>>> name_list[1] = 'dave'
>>> name_list
['sean', 'dave', 'tom', 'jack', 'Angelia', 'Daisy', 'jack', 'sary']
#连起来可以这样写
>>> name_list[name_list.index('alex')] = 'dave'
7.删除用户sean
删除总计有3种方法,无论使用那种方法 如果列表中指定的元素有多个,那么删除的将是最靠前的一个
#第一种删除的方法是制定元素名字
>>> name_list
['sean', 'dave', 'tom', 'jack', 'Angelia', 'Daisy', 'jack', 'sary']
>>> name_list.remove('sean')
>>> name_list
['dave', 'tom', 'jack', 'Angelia', 'Daisy', 'jack', 'sary']
#这种方法也是可以的,但是这种方法如果不输入后面的下标[0],默认删除了这个列表,个人感觉存在危险,但是貌似提高B格
>>> name_list
['sean', 'dave', 'tom', 'jack', 'Angelia', 'Daisy', 'jack', 'sary']
>>> del name_list[0]
>>> name_list
['dave', 'tom', 'jack', 'Angelia', 'Daisy', 'jack', 'sary']
#这种方法如果不指定删除的元素的下标,默认会删除最后一个元素。
>>> name_list
['sean', 'dave', 'tom', 'jack', 'Angelia', 'Daisy', 'jack', 'sary']
>>> name_list.pop()
'sary'
>>> name_list
['sean', 'dave', 'tom', 'jack', 'Angelia', 'Daisy', 'jack']
>>> name_list.pop(0)
['dave', 'tom', 'jack', 'Angelia', 'Daisy', 'jack']
8.获取列表元素指定的某个元素下标
#如果列表中某个元素有两个或者多个,那么返回的下标为第一个元素的下标
>>> name_list
['sean', 'dave', 'tom', 'jack', 'Angelia', 'Daisy', 'jack']
>>> name_list.index('jack')
3
9.统计列表中某个元素有多少个
>>> name_list
['sean', 'dave', 'tom', 'Angelia', 'Daisy', 'jack', 'jack']
>>> name_list.count('jack')
2
10.反转这个列表的数据
>>> name_list
['jack', 'jack', 'Daisy', 'Angelia', 'tom', 'dave', 'sean']
>>> name_list.reverse()
>>> name_list
['sean', 'dave', 'tom', 'Angelia', 'Daisy', 'jack', 'jack']
11.对列表进行排序,此排序是按照ASCII表进行排序的。
>>> name_list
['sean', 'dave', 'tom', 'Angelia', 'Daisy', 'jack', 'jack']
>>> name_list.sort()
>>> name_list
['Angelia', 'Daisy', 'dave', 'jack', 'jack', 'sean', 'tom']
12.把一个列表扩展到另外一个列表中
>>> name_list_2 = ['YunWei','KaiFa','ChanPin']
>>> name_list
['Angelia', 'Daisy', 'dave', 'jack', 'jack', 'sean', 'tom']
>>> name_list.extend(name_list_2)
>>> name_list
['Angelia', 'Daisy', 'dave', 'jack', 'jack', 'sean', 'tom', 'YunWei', 'KaiFa', 'ChanPin']
13.列表的“深浅cp”
我们知道列表中可以嵌套列表,也可以嵌套人和东西,但是它们并不是真正把小列表嵌套到里面,而是在这个地方指向的小列表的内存地址。
#####浅copy######
#查看一下name_list这个列表
>>> name_list
['Angelia', 'Daisy', 'dave', 'jack', 'jack', 'sean', 'tom', 'YunWei', 'KaiFa', 'ChanPin']
#向这个列表中插入一个列表[1,2,3]
>>> name_list.append([1,2,3])
>>> name_list
['Angelia', 'Daisy', 'dave', 'jack', 'jack', 'sean', 'tom', 'YunWei', 'KaiFa', 'ChanPin', [1, 2, 3]]
#copy namt_list 到 name_list_2,浅copy一共有四种方法,name_list_2 = copy.copy(name_list),name_list_2 = name_list[:],name_list_2 = list(name_list)
>>> name_list_2 = name_list.copy()
>>> name_list_2
['Angelia', 'Daisy', 'dave', 'jack', 'jack', 'sean', 'tom', 'YunWei', 'KaiFa', 'ChanPin', [1, 2, 3]]
>>> name_list
['Angelia', 'Daisy', 'dave', 'jack', 'jack', 'sean', 'tom', 'YunWei', 'KaiFa', 'ChanPin', [1, 2, 3]]
#更改name_list中的第1个元素为xiaoxin
>>> name_list[0] = 'xiaoxin'
>>> name_list
['xiaoxin', 'Daisy', 'dave', 'jack', 'jack', 'sean', 'tom', 'YunWei', 'KaiFa', 'ChanPin', [1, 2, 3]]
#我们看到更改了name_list后,name_list_2的第一个元素没有改变
>>> name_list_2
['Angelia', 'Daisy', 'dave', 'jack', 'jack', 'sean', 'tom', 'YunWei', 'KaiFa', 'ChanPin', [1, 2, 3]]
#把name_list中的最后一个列表元素中的第一个元素更改为4
>>> name_list[-1][0] =4
#此时我们发现两个列表中的列表元素全都变了
>>> name_list
['xiaoxin', 'Daisy', 'dave', 'jack', 'jack', 'sean', 'tom', 'YunWei', 'KaiFa', 'ChanPin', [4, 2, 3]]
>>> name_list_2
['Angelia', 'Daisy', 'dave', 'jack', 'jack', 'sean', 'tom', 'YunWei', 'KaiFa', 'ChanPin', [4, 2, 3]]
######深copy#######
#导入一个copy的模块
>>> import copy
#使用这个模块中的copy函数>>> name_list_2 = copy.deepcopy(name_list)
#两个列表是相同的
>>> name_list
['xiaoxin', 'Daisy', 'dave', 'jack', 'jack', 'sean', 'tom', 'YunWei', 'KaiFa', 'ChanPin', [4, 2, 3]]
>>> name_list_2
['xiaoxin', 'Daisy', 'dave', 'jack', 'jack', 'sean', 'tom', 'YunWei', 'KaiFa', 'ChanPin', [4, 2, 3]]
#分别更改第一个列表中第一个元素和小列表中的第一个元素,查看两个的区别
>>> name_list[0] = 'CeShi'
>>> name_list
['CeShi', 'Daisy', 'dave', 'jack', 'jack', 'sean', 'tom', 'YunWei', 'KaiFa', 'ChanPin', [4, 2, 3]]
>>> name_list_2
['xiaoxin', 'Daisy', 'dave', 'jack', 'jack', 'sean', 'tom', 'YunWei', 'KaiFa', 'ChanPin', [4, 2, 3]]
>>> name_list[-1][0] = 1
>>> name_list
['CeShi', 'Daisy', 'dave', 'jack', 'jack', 'sean', 'tom', 'YunWei', 'KaiFa', 'ChanPin', [1, 2, 3]]
>>> name_list_2
['xiaoxin', 'Daisy', 'dave', 'jack', 'jack', 'sean', 'tom', 'YunWei', 'KaiFa', 'ChanPin', [4, 2, 3]]
讲解一下为什么会出现这种状况:
由于列表后期存放的东西会超级大,那么我们假如真的复制了一个列表,这对系统的负载将是不敢想象的,所以python在这方面做了处理,如果列表中包含了列表那么复制这个列
表的情况只会复制第一层,也就是说下面的一层不会复制,如果还不明白,那我们就来看图
可能有人会问了,那这深浅copy到底有什么用呢?那我们来讲讲这个浅copy的用处,他可以用来做一个联合账号,看例子:
#首先做一个person的列表模版,里面放人和这个人的存款
>>> person = ['name',['money',100]]
>>> p1 = person[:]
>>> p2 = person[:]
>>> p1
['name', ['money', 100]]
>>> p2
['name', ['money', 100]]
#这里p1和p2是一个夫妻关系,当p1用户消费了50块钱,那么p2的帐号也消费了50块钱
>>> p1[0] = 'alex'
>>> p2[0] = 'fenjie'
>>> p1[1][1] = '50'
>>> p1
['alex', ['money', '50']]
>>> p2
['fenjie', ['money', '50']]
元组
元组一共有2个方法,分别为统计某个元素出现的次数和查询某个元素的下标
>>> mysql = ('Server IP','Server Passwd')
>>> mysql.index('Server IP')
0
>>> mysql.count('Server IP')
1
列表练习
写一个购物车的程序
需求:
- 启动程序后,让用户输入工资,然后打印商品列表
- 允许用户根据商品编号购买商品
- 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
- 可随时退出,退出时,打印已购买商品和余额
1 # Author:Sean sir
2 shopping_list = [('Car', 20000), ('Iphone', 6999), ('MacBookPro', 12999), ('Alex python', 30), ('T-shirt', 199)]
3 shopping_cart_list = []
4 salary = input('请问你的工资是多少: ')
5 if salary.isdigit():
6 salary = int(salary)
7 elif salary == 'q':
8 exit()
9 else:
10 print('输入一个正确的工资格式吧!他应该是一个正整数的类型!')
11 while True:
12 for index, item in enumerate(shopping_list):
13 print(index, item)
14 user_choice = input('您要买啥呢?>>>')
15 if user_choice.isdigit():
16 user_choice = int(user_choice)
17 if 0 <= user_choice < len(shopping_list): # 判断用户输入的是否大于0且小于总的产品数量
18 if salary > shopping_list[user_choice][1]: # 判断用户工资是否大于产品价格
19 salary -= shopping_list[user_choice][1] # 减掉总钱数
20 shopping_cart_list.append(shopping_list[user_choice][0]) # 把产品加入购物车的列表
21
22 else:
23 print('都没钱了,\033[31;1m汪哥\033[0m都急眼了,还买个屁啊!')
24 else:
25 print('请守规矩,输入一个正确的产品编号吧!不然没得玩了!')
26 elif user_choice == 'q':
27 print('您成功购买了如下产品:')
28 for product in shopping_cart_list:
29 print(product)
30 print('您的钱包还剩%s,请斟酌您的开支!' %salary)
31 break
32 else:
33 print('请守规矩,输入一个正确的产品编号吧!不然没得玩了!-->')
View Code
字符串方法介绍
#capitalize() 大写字符串首字母
1 def capitalize(self): # real signature unknown; restored from __doc__
2 """
3 S.capitalize() -> str
4
5 Return a capitalized version of S, i.e. make the first character
6 have upper case and the rest lower case.
7 """
8 return ""
9 eg:
10 name = 'sean xin'
11 print(name.capitalize())
capitalize()
#count() 统计字符串中某个字符出现的次数
1 def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
2 2 """
3 3 S.count(sub[, start[, end]]) -> int
4 4
5 5 Return the number of non-overlapping occurrences of substring sub in
6 6 string S[start:end]. Optional arguments start and end are
7 7 interpreted as in slice notation.
8 8 """
9 9 return 0
10 10
11 11 eg:
12 12 # Author:Sean sir
13 13 name = 'sean xinzhiyu'
14 14 print(name.count('i'))
15 15 2
count
#center 美观打印,打印包括现有变量在内的50个字符串, 如果字符串不够实用相应的字符填充
1 #打印包括字符串name在内的50个字符,如果name不够,用‘-’填充
2 >>> name = 'sean sir'
3 >>> name.center(50,'-')
4 >>> print(name.center(50,'-'))
5 ---------------------sean sir---------------------
center
#encond 在py3中吧字符串专为二进制
1 def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__
2 """
3 S.encode(encoding='utf-8', errors='strict') -> bytes
4
5 Encode S using the codec registered for encoding. Default encoding
6 is 'utf-8'. errors may be given to set a different error
7 handling scheme. Default is 'strict' meaning that encoding errors raise
8 a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
9 'xmlcharrefreplace' as well as any other name registered with
10 codecs.register_error that can handle UnicodeEncodeErrors.
11 """
12 return b""
13 eg:
14 >>> name = '我爱北京天安门'
15 >>> print(name.encode('utf-8'))
16 b'\xe6\x88\x91\xe7\x88\xb1\xe5\x8c\x97\xe4\xba\xac\xe5\xa4\xa9\xe5\xae\x89\xe9\x97\xa8'
encode
#endswith 判断一个字符串以什么结尾
1 def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
2 """
3 S.endswith(suffix[, start[, end]]) -> bool
4
5 Return True if S ends with the specified suffix, False otherwise.
6 With optional start, test S beginning at that position.
7 With optional end, stop comparing S at that position.
8 suffix can also be a tuple of strings to try.
9 """
10 return False
11 eg:
12 >>> name = 'xinzhiyu'
13 >>> mail = 'xinzhiyu@126.com'
14 >>> print(name.endswith('.com'))
15 False
16 >>> print(mail.endswith('.com'))
17 True
18 >>>
endswith
#expandtabs 如果字符串中包含一个\t的字符,那么实用这个方法,可以在打印的时候把\t转换为指定个数的空格
1 def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__
2 """
3 S.expandtabs(tabsize=8) -> str
4
5 Return a copy of S where all tab characters are expanded using spaces.
6 If tabsize is not given, a tab size of 8 characters is assumed.
7 """
8 return ""
9 eg:
10 >>> mail = 'xiaoxinzhiyu\t@126.com'
11 >>> print(mail)
12 xiaoxinzhiyu @126.com
13 >>> print(mail.expandtabs(tabsize = 30))
14 xiaoxinzhiyu @126.com
expandtabs
#find 查找一个字符或多个字符在一个字符串中的索引位置,索引位置从0开始,字符串可以根据索引进行切片
1 def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
2 """
3 S.find(sub[, start[, end]]) -> int
4
5 Return the lowest index in S where substring sub is found,
6 such that sub is contained within S[start:end]. Optional
7 arguments start and end are interpreted as in slice notation.
8
9 Return -1 on failure.
10 """
11 return 0
12 eg:
13 >>> mail
14 'xiaoxinzhiyu\t@126.com'
15 >>> print(mail.find('i'))
16 1
17 >>> print(mail.find('6'))
18 16
find
#format 这是一种文件格式化的输出,有两种方式
1 def format(self, *args, **kwargs): # known special case of str.format
2 """
3 S.format(*args, **kwargs) -> str
4
5 Return a formatted version of S, using substitutions from args and kwargs.
6 The substitutions are identified by braces ('{' and '}').
7 """
8 pass
9 eg:
10 >>> info = '''
11 ... name:{_name}
12 ... age:{_age}
13 ... '''
14 >>> print(info.format(_name='sean',_age='29'))
15
16 name:sean
17 age:29
18
19 format
20
21 eg:
22 >>> info = '''
23 ... name:{0}
24 ... age:{1}
25 ... '''
26 >>> print(info.format('sean','29'))
27
28 name:sean
29 age:29
30
31 >>>
format
#使用字典的方式格式化输出一个字符串
1 def format_map(self, mapping): # real signature unknown; restored from __doc__
2 """
3 S.format_map(mapping) -> str
4
5 Return a formatted version of S, using substitutions from mapping.
6 The substitutions are identified by braces ('{' and '}').
7 """
8 return ""
9 eg:
10 >>> info = '''
11 ... name:{_name}
12 ... age:{_age}
13 ... '''
14 >>> print(info.format_map({'_name':'sean','_age':'27'}))
15
16 name:sean
17 age:27
18
19 >>>
20
format_map
#index 返回某个字符在字符串的下标
1 def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
2 """
3 S.index(sub[, start[, end]]) -> int
4
5 Like S.find() but raise ValueError when the substring is not found.
6 """
7 return 0
8 eg:
9 >>> name = 'sean'
10 >>> print(name.index('e'))
11 1
index
#isalnum 判断这个字符串是否为单单有阿拉伯字母和数字组成
1 def isalnum(self): # real signature unknown; restored from __doc__
2 """
3 S.isalnum() -> bool
4
5 Return True if all characters in S are alphanumeric
6 and there is at least one character in S, False otherwise.
7 """
8 return False
9 eg:
10 >>> info = '''
11 ... name:{_name}
12 ... age:{_age}
13 ... '''
14 >>> name = 'sean'
15 >>> name2 = '123'
16 >>> name3 = '123'
17 >>> print(info.isalnum())
18 False
19 >>> print(name.isalnum())
20 True
21 >>> print(name2.isalnum())
22 True
23 >>> print(name3.isalnum())
24 True
25 >>>
26
isalnum
#isalpha 判断字符串是否由纯英文,包括大小字母
1 def isalpha(self): # real signature unknown; restored from __doc__
2 """
3 S.isalpha() -> bool
4
5 Return True if all characters in S are alphabetic
6 and there is at least one character in S, False otherwise.
7 """
8 return False
9 eg:
10 >>> name = 'sean'
11 >>> name2 = '123'
12 >>> name3 = 'ABdf'
13 >>> print(name.isalpha())
14 True
15 >>> print(name2.isalpha())
16 False
17 >>> print(name3.isalpha())
18 True
isalpha
#isdigit 判断是不是一个整数
1 def isdigit(self): # real signature unknown; restored from __doc__
2 """
3 S.isdigit() -> bool
4
5 Return True if all characters in S are digits
6 and there is at least one character in S, False otherwise.
7 """
8 return False
9 eg:
10 >>> name = '12F'
11 >>> name2 = '123'
12 >>> name3 = '122.3'
13 >>> print(name.isdecimal())
14 False
15 >>> print(name2.isdecimal())
16 True
17 >>> print(name3.isdecimal())
18 False
isdigit
#isidentifier 判断是不是一个合法的标示符,说白了就是说不是一个合法的变量名
1 def isidentifier(self): # real signature unknown; restored from __doc__
2 """
3 S.isidentifier() -> bool
4
5 Return True if S is a valid identifier according
6 to the language definition.
7
8 Use keyword.iskeyword() to test for reserved identifiers
9 such as "def" and "class".
10 """
11 return False
12 eg:
13 >>> name = '12F'
14 >>> name2 = '-name'
15 >>> name3 = '_1223'
16 >>> print(name.isidentifier())
17 False
18 >>> print(name2.isidentifier())
19 False
20 >>> print(name3.isidentifier())
21 True
isidentifier
#islower 判断字符串是不是不包涵大写
1 def islower(self): # real signature unknown; restored from __doc__
2 """
3 S.islower() -> bool
4
5 Return True if all cased characters in S are lowercase and there is
6 at least one cased character in S, False otherwise.
7 """
8 return False
9 eg:
10 >>> name = '12F'
11 >>> name2 = '-n!a4me'
12 >>> name3 = '_1223'
13 >>> print(name.islower())
14 False
15 >>> print(name2.islower())
16 True
17 >>> print(name3.islower())
18 False
islower
#isnumeric 判断字符串是否只有数字
1 def isnumeric(self): # real signature unknown; restored from __doc__
2 """
3 S.isnumeric() -> bool
4
5 Return True if there are only numeric characters in S,
6 False otherwise.
7 """
8 return False
9 eg:
10 >>> name = '12F'
11 >>> name2 = '-n!a4me'
12 >>> name3 = '223'
13 >>> print(name.isnumeric())
14 False
15 >>> print(name2.isnumeric())
16 False
17 >>> print(name3.isnumeric())
18 True
isnumeric
#isprintable 如果字符串中有制表符\t那么返回false,否则为true,alex说是判断是否可打印的,加一句,忘记他吧!
1 def isprintable(self): # real signature unknown; restored from __doc__
2 """
3 S.isprintable() -> bool
4
5 Return True if all characters in S are considered
6 printable in repr() or S is empty, False otherwise.
7 """
8 return False
9 eg:
10 >>> name = '12F'
11 >>> name2 = '-n!a4me '
12 >>> name3 = 'ss\t'
13 >>> print(name.isprintable())
14 True
15 >>> print(name2.isprintable())
16 True
17 >>> print(name3.isprintable())
18 False
isprintable
#isspace 判断字符串是否为一个空格
1 def isspace(self): # real signature unknown; restored from __doc__
2 """
3 S.isspace() -> bool
4
5 Return True if all characters in S are whitespace
6 and there is at least one character in S, False otherwise.
7 """
8 return False
9 eg:
10 >>> name = '12F'
11 >>> name2 = '-n!a4me '
12 >>> name3 = ' '
13 >>> print(name.isspace())
14 False
15 >>> print(name2.isspace())
16 False
17 >>> print(name3.isspace())
18 True
isspace
#istitle 判断一个字符串是否为title,字符串首字母大写就为title
1 def istitle(self): # real signature unknown; restored from __doc__
2 """
3 S.istitle() -> bool
4
5 Return True if S is a titlecased string and there is at least one
6 character in S, i.e. upper- and titlecase characters may only
7 follow uncased characters and lowercase characters only cased ones.
8 Return False otherwise.
9 """
10 return False
11 eg:
12 >>> name = '12Fila Asde'
13 >>> name2 = 'my name is ?'
14 >>> name3 = ' My Name Is ?'
15 >>> print(name.istitle())
16 True
17 >>> print(name2.istitle())
18 False
19 >>> print(name3.istitle())
20 True
istitle
#isupper 判断字符串是否为全部大写
1 def isupper(self): # real signature unknown; restored from __doc__
2 """
3 S.isupper() -> bool
4
5 Return True if all cased characters in S are uppercase and there is
6 at least one cased character in S, False otherwise.
7 """
8 return False
9 eg:
10 >>> name = '12Fs'
11 >>> name2 = '-n!a4me\t'
12 >>> name3 = '12FS'
13 >>> print(name.isupper())
14 False
15 >>> print(name2.isupper())
16 False
17 >>> print(name3.isupper())
18 True
isupper
#join 最常见用法为,把一个列表拼成一个字符串,中间用这个字符串链接
1 def join(self, iterable): # real signature unknown; restored from __doc__
2 """
3 S.join(iterable) -> str
4
5 Return a string which is the concatenation of the strings in the
6 iterable. The separator between elements is S.
7 """
8 return ""
9 eg:
10 >>> li = ['1','2','3']
11 >>> print(' '.join(li))
12 1 2 3
join
#lower 把所有的字符串都变为小写
1 def lower(self): # real signature unknown; restored from __doc__
2 """
3 S.lower() -> str
4
5 Return a copy of the string S converted to lowercase.
6 """
7 return ""
8 eg:
9 >>> name = '12Fs'
10 >>> name2 = '-n!a4me\t'
11 >>> name3 = '12FS'
12 >>> print(name.lower())
13 12fs
14 >>> print(name2.lower())
15 -n!a4me
16 >>> print(name3.lower())
17 12fs
lower
#lstrip 去掉左边的空格以及tab制表符
1 def lstrip(self, chars=None): # real signature unknown; restored from __doc__
2 """
3 S.lstrip([chars]) -> str
4
5 Return a copy of the string S with leading whitespace removed.
6 If chars is given and not None, remove characters in chars instead.
7 """
8 return ""
9 eg:
10 >>> name = ' 12Fs'
11 >>> name2 = '-n!a4me\t '
12 >>> name3 = ' 12FS '
13 >>> print(name.lstrip())
14 12Fs
15 >>> print(name2.lstrip())
16 -n!a4me
17 >>> print(name3.lstrip())
18 12FS
lstrip
#ljust 打印固定长度的字符串,如果不够在字符串的右边补充指定字符
1 def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__
2 """
3 S.ljust(width[, fillchar]) -> str
4
5 Return S left-justified in a Unicode string of length width. Padding is
6 done using the specified fill character (default is a space).
7 """
8 return ""
9 eg:
10 >>> name3 = '12FS'
11 >>> print(name3.ljust(50,'*'))
12 12FS**********************************************
ljust
#maketrans 这个方法要配合translate方法使用,对数据进行加密
1 def maketrans(self, *args, **kwargs): # real signature unknown
2 """
3 Return a translation table usable for str.translate().
4
5 If there is only one argument, it must be a dictionary mapping Unicode
6 ordinals (integers) or characters to Unicode ordinals, strings or None.
7 Character keys will be then converted to ordinals.
8 If there are two arguments, they must be strings of equal length, and
9 in the resulting dictionary, each character in x will be mapped to the
10 character at the same position in y. If there is a third argument, it
11 must be a string, whose characters will be mapped to None in the result.
12 """
13 pass
14 eg:
15 p = name.maketrans('abcde','12345')
16 print('test'.translate(p))
maketrans
#replace 替换把指定字符串的某字符换位另外字符,也可以指定替换的次数
1 def replace(self, old, new, count=None): # real signature unknown; restored from __doc__
2 """
3 S.replace(old, new[, count]) -> str
4
5 Return a copy of S with all occurrences of substring
6 old replaced by new. If the optional argument count is
7 given, only the first count occurrences are replaced.
8 """
9 return ""
10 eg:
11 >>> name = '12345'
12 >>> name2 = 'abacdae'
13 >>> print(name.replace('1','2'))
14 22345
15 >>> print(name2.replace('a','B',2))
16 BbBcdae
replace
#rfind 查找一个字符串中某个字符所在的索引,如果这个字符串中有多个这个字符,那么会找到最右边的那个字符
1 def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
2 """
3 S.rfind(sub[, start[, end]]) -> int
4
5 Return the highest index in S where substring sub is found,
6 such that sub is contained within S[start:end]. Optional
7 arguments start and end are interpreted as in slice notation.
8
9 Return -1 on failure.
10 """
11 return 0
12 eg:
13 >>> name2 = 'abacdae'
14 >>> print(name2.rfind('a'))
15 5
rfind
#rindex 和rfind没什么区别
1 def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
2 """
3 S.rindex(sub[, start[, end]]) -> int
4
5 Like S.rfind() but raise ValueError when the substring is not found.
6 """
7 return 0
8 eg:
9 >>> name2 = 'abacdae'
10 >>> print(name2.rindex('a'))
11 5
rindex
#rjust 打印固定长度的字符串,如果不够在字符串的左边补充指定字符
1 def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__
2 """
3 S.rjust(width[, fillchar]) -> str
4
5 Return S right-justified in a string of length width. Padding is
6 done using the specified fill character (default is a space).
7 """
8 return ""
9 eg:
10 >>> print(name2.rjust(50,'-'))
11 -------------------------------------------abacdae
rjust
#rsplit 是从右开始切片,当不指定切片的个数的时候,默认和split没有区别,但是当指定了切片个数后,就会有所不同了
1 def rsplit(self, *args, **kwargs): # real signature unknown
2 """
3 Return a list of the sections in the bytearray, using sep as the delimiter.
4
5 sep
6 The delimiter according which to split the bytearray.
7 None (the default value) means split on ASCII whitespace characters
8 (space, tab, return, newline, formfeed, vertical tab).
9 maxsplit
10 Maximum number of splits to do.
11 -1 (the default value) means no limit.
12
13 Splitting is done starting at the end of the bytearray and working to the front.
14 """
15 pass
16 eg:
17 name2 = 'aaaaaaaaa'
18 >>> print(name2.rsplit('a',3))
19 ['aaaaaa', '', '', '']
rsplit
#rstrip 去掉右边的空格以及tab制表符
1 def rstrip(self, *args, **kwargs): # real signature unknown
2 """
3 Strip trailing bytes contained in the argument.
4
5 If the argument is omitted or None, strip trailing ASCII whitespace.
6 """
7 pass
8 eg:
9 >>> name2 = ' aaaaaaaaa '
10 >>> print(name2.rstrip())
11 aaaaaaaaa
rstrip
#split 使用指定分隔符对字符串进行分片,最后得到一个列表
1 def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
2 """
3 S.split(sep=None, maxsplit=-1) -> list of strings
4
5 Return a list of the words in S, using sep as the
6 delimiter string. If maxsplit is given, at most maxsplit
7 splits are done. If sep is not specified or is None, any
8 whitespace string is a separator and empty strings are
9 removed from the result.
10 """
11 return []
12 eg:
13 >>> name2 = 'abacdae'
14 >>> print(name2.split('a'))
15 ['', 'b', 'cd', 'e']
split
#splitlines 使用回车符进行字符串分片,最后得到一个列表
1 def splitlines(self, keepends=None): # real signature unknown; restored from __doc__
2 """
3 S.splitlines([keepends]) -> list of strings
4
5 Return a list of the lines in S, breaking at line boundaries.
6 Line breaks are not included in the resulting list unless keepends
7 is given and true.
8 """
9 return []
10 eg:
11 >>> name2 = 'aba\ncdae'
12 >>> print(name2.splitlines())
13 ['aba', 'cdae']
splitlines
#startswith 以什么结尾
1 def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__
2 """
3 S.startswith(prefix[, start[, end]]) -> bool
4
5 Return True if S starts with the specified prefix, False otherwise.
6 With optional start, test S beginning at that position.
7 With optional end, stop comparing S at that position.
8 prefix can also be a tuple of strings to try.
9 """
10 return False
11 eg:
12 >>> name2 = 'aba\ncdae'
13 >>> print(name2.startswith('a'))
14 True
15 >>> print(name2.startswith('e'))
16 False
startswith
#strip 去除字符串两边的空格和换行
1 def strip(self, chars=None): # real signature unknown; restored from __doc__
2 """
3 S.strip([chars]) -> str
4
5 Return a copy of the string S with leading and trailing
6 whitespace removed.
7 If chars is given and not None, remove characters in chars instead.
8 """
9 return ""
10 eg:
11 >>> name2 = ' aba\ncdae\n '
12 >>> print(name2.strip())
13 aba
14 cdae
strip
#swapcase 大小写互换
1 def swapcase(self): # real signature unknown; restored from __doc__
2 """
3 S.swapcase() -> str
4
5 Return a copy of S with uppercase characters converted to lowercase
6 and vice versa.
7 """
8 return ""
9 eg:
10 >>> name2 = ' aba\ncDae\n '
11 >>> print(name2.swapcase())
12 ABA
13 CdAE
14
swapcase
#title 把一个字符串变为一个title
1 def title(self): # real signature unknown; restored from __doc__
2 """
3 S.title() -> str
4
5 Return a titlecased version of S, i.e. words start with title case
6 characters, all remaining cased characters have lower case.
7 """
8 return ""
9 eg:
10 >>> name2 = ' my name is ? '
11 >>> print(name2.title())
12 My Name Is ?
title
#translate 配合maketrans进行字符串的交换
1 def translate(self, table): # real signature unknown; restored from __doc__
2 """
3 S.translate(table) -> str
4
5 Return a copy of the string S in which each character has been mapped
6 through the given translation table. The table must implement
7 lookup/indexing via __getitem__, for instance a dictionary or list,
8 mapping Unicode ordinals to Unicode ordinals, strings, or None. If
9 this operation raises LookupError, the character is left untouched.
10 Characters mapped to None are deleted.
11 """
12 return ""
13 eg:
14 p = name.maketrans('abcde','12345')
15 print('test'.translate(p))
translate
#upper 把字符串都变换为大写
1 def upper(self): # real signature unknown; restored from __doc__
2 """
3 S.upper() -> str
4
5 Return a copy of S converted to uppercase.
6 """
7 return ""
8 eg:
9 >>> name2 = ' my name is ? '
10 >>> print(name2.upper())
11 MY NAME IS ?
upper
#zfill 打印指定长度字符串,不够的使用0在左边补充
1 def zfill(self, width): # real signature unknown; restored from __doc__
2 """
3 S.zfill(width) -> str
4
5 Pad a numeric string S with zeros on the left, to fill a field
6 of the specified width. The string S is never truncated.
7 """
8 return ""
9 eg:
10 >>> name2 = ' my name is ? '
11 >>> print(name2.zfill(50))
12 000000000000000000000000000000000 my name is ?
zfill
字典的使用
info = {
'stu1101': "TengLan Wu",
'stu1102': "LongZe Luola",
'stu1103': "XiaoZe Maliya",
}
字典的特性:天生去重,天生无序
字典的增加:
>>> info = {
... 'stu1101': "TengLan Wu",
... 'stu1102': "LongZe Luola",
... 'stu1103': "XiaoZe Maliya",
... }
>>>
>>>
>>>
>>> info
{'stu1103': 'XiaoZe Maliya', 'stu1102': 'LongZe Luola', 'stu1101': 'TengLan Wu'}
>>> info['stu1104'] = 'alex'
>>> info
{'stu1104': 'alex', 'stu1103': 'XiaoZe Maliya', 'stu1102': 'LongZe Luola', 'stu1101': 'TengLan Wu'}
字典的修改:
>>> info['stu1104'] = 'fengjie'
>>> info
{'stu1104': 'fengjie', 'stu1103': 'XiaoZe Maliya', 'stu1102': 'LongZe Luola', 'stu1101': 'TengLan Wu'}
字典的删除:
#这是标准的删除方式
>>> info.pop('stu1104')
'fengjie'
>>> info
{'stu1103': 'XiaoZe Maliya', 'stu1102': 'LongZe Luola', 'stu1101': 'TengLan Wu'}
#这个是一个提高逼格的删除方式
>>> info
{'stu1103': 'XiaoZe Maliya', 'stu1102': 'LongZe Luola', 'stu1101': 'TengLan Wu'}
>>> del info['stu1103']
>>> info
{'stu1102': 'LongZe Luola', 'stu1101': 'TengLan Wu'}
#这个是随机删除列表中的一条数据
>>> info
{'stu1102': 'LongZe Luola', 'stu1101': 'TengLan Wu'}
>>> info.popitem()
('stu1102', 'LongZe Luola')
>>> info
{'stu1101': 'TengLan Wu'}
删除整个字典
>>> info
{'stu1101': 'TengLan Wu'}
>>> del info
>>> info
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'info' is not defined
字典的查询
>>> info = {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'}
#查询某个key是否在这个字典中
>>> "stu1102" in info
True
#获取一个vlue,如果这个key不再,不会报错,而是返回一个none
>>> info.get("stu1102")
'LongZe Luola'
#也是获取一个字典中的value
>>> info["stu1102"]
'LongZe Luola'
#但是当获取一个不存在的key,那么就会报错了
>>> info["stu1105"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'stu1105'
关于字典的其他方法
#clear 清空整个字典
>>> name = {'k1':'v1','k2':'v2','k3':'v3'}
>>> print(name)
{'k1': 'v1', 'k3': 'v3', 'k2': 'v2'}
>>> name.clear()
>>> print(name)
{}
#copy 复制一个字典到
name = {'k1':'v1','k2':'v2','k3':'v3'}
name2 = name.copy()
print(name2)
print(name)
#output
{'k3': 'v3', 'k1': 'v1', 'k2': 'v2'}
{'k3': 'v3', 'k1': 'v1', 'k2': 'v2'}
#fromkeys 定义一个默认的字典
>>> dic = dict.fromkeys([6,7,8],['my name is sean!','123'])
>>> print(dic)
{8: ['my name is sean!', '123'], 6: ['my name is sean!', '123'], 7: ['my name is sean!', '123']}
据说这里有一个坑,但是我觉得这并不叫坑,大概意思就是如果定义了一个默认的字典,字典的key是一个列表的情况下,那么更改任意一个key的列表内容,其它
key的valu也就是列表也会改变的,继续看:
>>> print(dic)
{8: ['my name is sean!', '123'], 6: ['my name is sean!', '123'], 7: ['my name is sean!', '123']}
>>> dic[8]
['my name is sean!', '123']
>>> dic[8][1] = '456'
>>> dic
{8: ['my name is sean!', '456'], 6: ['my name is sean!', '456'], 7: ['my name is sean!', '456']}
#items 把整个字典的key-value当作一个元组的元素存放到一个列表中
>>> dic = dict.fromkeys([6,7,8],['my name is sean!','123'])
>>> print(dic.items())
dict_items([(8, ['my name is sean!', '123']), (6, ['my name is sean!', '123']), (7, ['my name is sean!', '123'])])
#keys 把整个字典的key存放到一个列表中
>>> dic = dict.fromkeys([6,7,8],['my name is sean!','123'])
>>> print(dic.keys())
dict_keys([8, 6, 7])
#setdefault 当查找一个key的时候,如果这个key在这个字典中,那么返回key的对应值;如果这个key不再这个字典中,那么返回setdefault传入的参数
>>> dic
{'8': ['99999', '999999'], 6: ['my name is sean!', '123'], '9': ['99999', '999999'], 8: ['my name is sean!', '123'], 9: ['99999', '999999'], 7: ['my name is sean!', '123']}
#dic这个字典中有key为8的值
>>> dic.setdefault(8,['99999','999999'])
['my name is sean!', '123']
#di这个字典中,没有key为9的值
>>> dic.setdefault(9,['99999','999999'])
['99999', '999999']
#update 更新一个字典,传入的参数为一个字典,也可以说是合并,但是被传入的那个字典还是存在的
>>> dic1 = {'a':'1','b':'2'}
>>> dic2 = {'c':'3'}
>>> dic1.update(dic2)
>>> print(dic1,dic2)
{'b': '2', 'a': '1', 'c': '3'} {'c': '3'}
#value 打印整个字典中的所有value
>>> dic1 = {'a':'1','b':'2'}>>> print(dic1.values())
dict_values(['2', '1'])
字典也是存在“深浅copy”的
import copy
name = {'k1':'v1','k2':'v2','k3':['1','2']}
#浅copy
name1 = copy.copy(name)
name['k3'][0] = '4'
print(name,name1)
#深copy
name2 = copy.deepcopy(name)
name['k3'] [0] = '3'
print(name2)
print(name)
#output
{'k2': 'v2', 'k3': ['4', '2'], 'k1': 'v1'} {'k2': 'v2', 'k1': 'v1', 'k3': ['4', '2']}
{'k2': 'v2', 'k1': 'v1', 'k3': ['4', '2']}
{'k2': 'v2', 'k3': ['3', '2'], 'k1': 'v1'}
便利整个字典
循环字典有两种方式:
name = {'k1':'v1','k2':'v2','k3':['1','2']}
# 方法一,不建议使用,因为在打印的时候,首先需要把字典转换成一个列表,这样当字典的数据很大的时候,会产生不要的时间垃圾
for k,v in name.items():
print(k,v)
# 方法二,通过key去查找
print('----------------')
for k in name:
print(k,name[k])
#output
k2 v2
k3 ['1', '2']
k1 v1
----------------
k2 v2
k3 ['1', '2']
k1 v1