文件类型
类型 | type | 创建方法 |
数字 | int可变 | a = 1 |
字符串 | str可变 | a = ("asv") 注:多个元素就是元组 |
元组 | tuple不可变 | b = ("asv","aed",21) |
列表(有序) | list可变 | c = ["asv","aed",21] |
字典(无序) | dict可变 | d ={"v1":"bb","v2":"b3"} |
集合(无序) | set可变 | se = {"one","tow","three"} |
-
文件类型转换
-
a = "xxx" print(a) #字符串类型 print(list(a)) #字符串转列表 print(tuple(a)) #字符串转元组 b = ["aa","bb","cc"] #列表 b=str(tuple(b)) #列表转元组 print(b) d = ("aa","bb","c") #元组 d = str(list(d)) #元组转列表 print(d)
-
数字
int 整型
Long 长整型 pytyon3没有
Float 浮点数 1个浮点数占8字节(64位) 浮点数:带有小数的整数)
bool布尔 (判断真或假 ) 1==True 0==False (只有0是False 其他都是True)
判断a列表是否存在元素 >>> a =['aa','cc'] >>> "bb" in a True >>> "dd" in a False
字符串
strip移除空白
>>> msg14=" adf " #前后有空格 >>> print(msg14.strip()) #去掉左右空格,()内可加字符 adf >>> print(msg14.rstrip()) #去掉右空格 adf >>> print(msg14.lstrip()) #去掉右空格 adf
split 分割
-
>>>user_1 = "aex|sb123|9" >>>v = user_1.split("|") #分割所有,以|为分开 >>>print (v) ['aex', 'sb123', '9'] >>>v = user_1.split("|",1) #分割第一个,从左边分割 >>>print (v) ['aex', 'sb123|9'] >>>v = user_1.rsplit("|",1)#分割第一个,从右边分割 >>>print (v) ['aex|sb123', '9']
长度 len(name)
按字符算 不是字节 >>> msg17=("abc ","aa") #多个元素显示元素个数,单个元素显示字符串个数 >>> print(len(msg17)) 2 >>> msg17=("abc") >>> print(len(msg17)) 3
索引 name[2]
>>> name [11, 'ad', 33] >>> name[2] 33
切片 a[:3] 或a[3:]或a[3]
>>> msg="nihao 123" >>> print(msg[1]) #范围 取位置1的值 i >>> print(msg[2:5]) #:表示顺序延伸 范围 取位置2-4的值 顾头不顾尾不取位置4的值 hao >>> print(msg[0:]) #:表示顺序延伸 范围 所有位置的值 nihao 123 >>> print(msg[0:-1]) #:表示顺序延伸 范围取值0到-2的值 顾头不顾尾不取位置-1的值 nihao 12
capitalize 首字母大写
>>> msg="hello world" >>> print(msg.capitalize()) Hello world
大写变小写
casefold >>>name ='AabbCc' >>>v = name.casefold() #lower也能实现 但不如casefold功能多,一般用casefold >>>print(v) aabbcc ------------------- lower >>>aa = ("AaBbCc") >>>aa=aa.lower() >>>print(aa) aabbcc
小写转大写
swapcase >>> name = "atlex" >>> result =name.swapcase() >>> print(result) ATLEX ---------------------- upper >>>aa = ("AaBbCc") >>>aa=aa.upper() >>>print(aa) AABBCC
center分割行
>>> mss="abc" >>> print(msg.center(20)) #20是总长度,默认空行是内容 abc >>> print(msg.center(20,"*")) #20是总长度,*行内容 *长度为1 print("msg".center(20,"*")) #加"" 不用定义变量 *******abc******** >>> print(msg.ljust(20,"*")) #20是总长度右边填充* abc****** >>> print(msg.rjust(20,"*")) #20是总长度左边填充* ******abc
count统计元素出现的次数
>>>name = "dfdfdaa,df,adsfasdfaga" >>>result = name.count("df",0,10) #统计:df出现的次数 范围:0-9个字符(有头无尾),注:不加0-10是统计所有字符 >>>print (result) 2 >>>result = name.count("df",0,-1) 右边第一个到左边第0个中间的df个数 >>>print (result) 3
encode utf-8转gbk
>>>name ="理解" >>>result= name.encode("gbk") >>>print(result) b'\xc0\xed\xbd\xe2'
endswith判断结尾数字 startswith判断结尾数字
>>> name ="adfasdfs" >>> result= name.endswith("fs") #是否以fs结尾 >>> result= name.endswith("s",0,5) #以s结尾 范围是大于等于0 小于5 判断是否为真 >>> print(result) True >>> name ="adfasdfs" >>> result= name.startswith("ad") #是否以ad开头 >>> result= name.startswith("a",0,5) #以s开头 范围是大于等于0 小于5 判断是否为真 >>> print(result) True
expandtabs增加分割符
-
>>> name = "a\tlex" >>>name = "a\tlex\tguolm\tqiqi\na\tb" ##\t是制表符,\n换行符 >>>result =name.expandtabs(20) #20是\t的行间距 >>>print(result)
partition字符分割
>>> name ="alexissb" >>> result= name.partition("is") #指定is为分割,分割成3段 >>> print(result) ('alex', 'is', 'sb')
find和index 查找字符串
>>> msg14="hello" >>> print(msg14.find("o")) #find 查找到元素,返回元素位置 4 >>> print(msg14.find("a")) #find 查找不到元素,返回-1 -1 >>> print(msg14.index("o")) #index 查找到元素,返回元素位置 4 >>> print(msg14.index("a")) #index 查找不到元素,报错 Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: substring not found
enumerate 定义下标
>>>li= ["eric","alex","tony"] >>>for i,ele in enumerate(li,1): #1是指定第一次为1, 不指定下标默认为零 >>> print(i,ele) 1 eric 2 alex 3 tony >>>v=input("请输入商品序号") >>>v=int(v) >>>item = li[v-1] #v-1表示:是数字v减1 ,因为定义序列下标为1, 如上使用默认就不用v-1 >>>print(item)
join元素拼接
>>> msg="aa哈站" >>> v="_".join(msg) >>> print(v) a_a_哈_站 >>> name=["aa","bb","cc"] #不能有数字 都是字符串 >>> v="_".join(name) #_可替换 只要for能循环的 .join都能用 >>> print(v) aa_bb_cc
format 拼接
>>> print('{0} {1} {0}'.format('name','age')) name age name >>> print ('{name}'.format(name='alex')) alex >>> print("{} {}".format("name","age")) name age >>> name="guolm {name} as {id}" >>> result = name.format(name="man",id="19") >>> print(result) guolm man as 19 tpl = "我是:{name},年龄:{age},性别:{gender}" v = tpl.format(name='李杰',age=19,gender='随意') print(v)
isalnum判断值是否由数字和字母或纯数字或纯字母组成
>>> msg="12aa" ##"aAaa" "122"都为true真 >>> print(msg.isalnum()) True >>> msg="122_aa" >>> print(msg.isalnum()) False
isdigit判断值为数字,整形(整数)
>>>ms=11 >>> print(ms.isdigit()) True真 >>> ms="101.1" >>> print(ms.isdigit()) False假 #错误
isalpha判断值由字母组成
>>> msg="Aaa" >>> print(msg.isalpha()) True >>> msg="122_aa" >>> print(msg.isalpha()) False
isspace全是空格
aa = " " #只针对字符串 print(aa.isspace()) True
isdecimal判断值为十进制
>>> ms="101" >>> print(ms.isdecimal()) True >>> ms="101.1" >>> print(ms.isdecimal()) False
islower判断值全是小写
>>>ad="aaa" >>>print(ad.islower()) True
isupper判断值全是大写
>>>ad="AAA" >>>print(ad.isupper()) True
maketrans对应关系替换
>>> msg16="my name is abcd" >>> table=str.maketrans("abcd","1234") #abcd和gulm长度必须相同 >>> print(msg16.translate(table)) my ngme is 1234
zfill填充
>>> msg17="abc" >>> print(msg17.zfill(20)) #不够的位数用0填充 00000000000000000abc
relpace转换,替换
>>> name ="aaxissb" >>> result= name.replace("a","g",2) #a转换成g 范围:前2个,不加数字表示转换全部 >>> print(result) ggxissb
元组
元组的元素不能改 但是元组的元素的元素可以修改,
元组结尾必须加逗号,
元组的参数count和index a = ('a',1,)
count统计元素出现的次数
index 查找字符串(查找不到报错)
元组嵌套字典
>>> t1 = (1,2,{"gg":"k3"}) #增加了字典 >>> t1 (1, 2, {'gg': 'k3'}) >>> t1[2]["gg"]=2 >>> t1 (1, 2, {'gg': 2})
列表
有序,元素可以更改, 更容易的存取多个信息
L = ["a",11,"var"] L.append("var") #追加一个,var的值添加到L的中 print(L)
追加多个元素 extend name = ["1","aa","cc","bb","33","22"] name.extend([55,"qq"]) print(name) 插入, 指定追加 insert
name = ["aa","var","cc","var","33","22"] name.insert(2,"bb") #在第三元素后增加bb print(name)
pop 指定索引删除元素 默认删除最后一个元素 >>>name = ["aa","var","cc","var","33","22"] >>>name.pop() #默认删除最后一个元素 >>>print(name) ['aa', 'var', 'cc', 'var', '33'] >>>test = ["aa","var","cc","var","33","22"] >>>test.pop(0) #指定可指定索引删除,0是第一个索引 >>>print(test) ['var', 'cc', 'var', '33', '22'] remove 删除,指定删除元素var 如有多个var 删除第一次出现元素var name = ["1","var","cc","var","33","22"] name.remove("var") print(name) del 根据索引删除 name = ["a",11,"var","cc","22","aaa"] print(name) #del name[0] #删除索引1的元素 del name[0:2] #删除指定索引的元素 print(name) count 显示元素aa出现个数 name = ["1","aa","cc","aa","33","22"] print(name.count("aa")) 显示元素的位置,没有就报错 index name = ["1","aa","cc","bb","33","22"] print(name.index("cc")) 排序 从小到大 sort name = ["1","aa","cc","bb","33","22"] name.sort() print(name) 反转排序 reverse name = ["1","aa","cc","bb","33","22"] name.reverse() print(name) 更新 a=['A','B'] a[1] = 'c' print(a) (结果 a = ['A','c'] )
字典
字典 无序
字典的key是不可变数据类型,只能用数字,字符串,元组表示. 例如dic={"1":"v1","k1":"v1","(2.k2)":"v3"}
dict = { key : value }
key定义规则:
不可变:数字,字符串,元组 可变:列表,字典
取字典子集中key的value
name = { "a":{"b":"aaa","c":"ccc"}, "v" : "vv" } print(name["a"]["c"])
增删改查
dic = {'name':'alex','age':["aa","bb"],} #查 print (dic.get('name')) #如果找不到name的vulue,返回None print (dic.get('name',"null")) #如果找不到name的vulue,指定返回null #增 dic['gender']='female' print(dic) #改 dic['name']='guolm' #改key dic['age'][0]='guolm' #改key中第一个value print (dic) #删 del和pop效果一样 del dic['name'] print (dic)
pop 删除指定key popitem(随机删除key)
-
>>>dic ={"a1":"v1","a2":"v2"} >>>dic.pop("a1") #必须指定key,key不存在,报错 >>>dic.pop("a1","aaa") #指定删除al,al不存在,指定返回aaa >>>print(dic) {'a2': 'v2'} >>>dic={"k1":"v1","k2":"v2"} >>>v = dic.pop("k1") #删除原dic的k1,并让v获取k1的values >>>print(v) v1 >>>print(dic) {'k2': 'v2'} >>>dic={"k1":"v1","k2":"v2","k3":"v3"} >>>print(dic) {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'} >>>k,v = dic.popitem()#删除原dic的最后一个key+values,把dic的最后一个key+values 赋值给k和v >>>print(dic) {'k1': 'v1', 'k2': 'v2'} >>>print(k,v) k3 v3 >>>print(k) k3 >>>print(v) v3 dic={"k1":"v1","k2":"v2","k3":"v3"} print(dic) {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'} v=dic.popitem() #删除原dic的最后一个key+values,把dic的最后一个key+values 赋值给v print(dic) {'k1': 'v1', 'k2': 'v2'} print(v[0],v[1]) k3 v3 print(v) {'k1': 'v1', 'k2': 'v2'}
update增key 合并2个字典
dic={"k1":"v1","k2":"v2","k3":"v3"} dic.update({"k3":"v4","k5":"v5"}) #key不存在,增加key+values,key存在改改values print(dic) {'k1': 'v1', 'k2': 'v2', 'k3': 'v4', 'k5': 'v5'} -------------------------- >>>dic = {'nn':'alex','age':["aa","bb"],} >>>gavin = {"aa":"bb","age":["aa","c3"],'nn':'al111111ex',} >>>dic.update(gavin) #合并2个字典,把gavin中key:value增加到dic,相同key相同vlaue或相同key不同vlaue,覆盖原dic的值 >>>print(dic) {'nn': 'al111111ex', 'age': ['aa', 'c3'], 'aa': 'bb'}
setdefault key不存在就新增,存在就查看
dic={"k1":"v1","k2":"v2","k3":"v3"} dic.setdefault("k3","v4") #key不存在,增加key+values,key存在,不改values print(dic) {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
items 显示所有项 多用于循环
>>> dic ={"a1":"v1","a2":"v2"} >>> print(dic.keys()) #显示所有key dict_keys(['a1', 'a2']) >>> print(dic.values()) #显示所有values dict_values(['v1', 'v2']) >>> print(dic.items()) #显示所有值 dict_items([('a1', 'v1'), ('a2', 'v2')]) dic= {"k1":"v1","k2":"v2"} for item in dic.items(): #items显示key+values print(item) print("------------------------------") for item in dic.keys(): #keys显示key print(item) print("------------------------------") for item in dic.values(): #values显示values print(item) print("------------------------------") ------------------------------------------------ dic = {'nn':'alex','age':["aa","bb"],} ##2个for 结果一样, 建议用上边的for,下边的for效率低 for key in dic: print(key,dic[key]) for k,v in dic.items(): print(k,v)
fromkeys多key定义相同valie
>>> name ={"a1":"v1"} >>> new_dict=name.fromkeys(["k1","k2","k3"],"v2") #k1,k2,k3,是key v2是value #内存地址相同 改一个全改 >>> print (new_dict) {'k1': 'v2', 'k2': 'v2', 'k3': 'v2'}
copy浅复制
-
>>>one = { "aa":"bb", "guolm":{"one":"1","tow":"2"}, 1:2, } tow与one的key和value相同 >>>tow = one.copy() >>>print (tow) {'aa': 'bb', 'guolm': {'one': '1', 'tow': '2'}, 1: 2} one第一层key和value改变,tow不改变 >>>one["aa"] = "cc" >>>print(one) {'aa': 'cc', 'guolm': {'one': '1', 'tow': '2'}, 1: 2} >>>print (tow) {'aa': 'bb', 'guolm': {'one': '1', 'tow': '2'}, 1: 2} one第二层key和value改变,tow也改变 >>>one["guolm"]["one"]= "3" >>>print(one) {'aa': 'bb', 'guolm': {'one': '3', 'tow': '2'}, 1: 2} >>>print(tow) {'aa': 'bb', 'guolm': {'one': '3', 'tow': '2'}, 1: 2} import copy three = one.copy,deepcopy() #完整复制one, one如何改变 three不改变
set无序集合
set是可变集合
集合没有索引 不能查看 能for循环
重复的元素不显示
isdis.joins 是否有交集
issubset 子集
父集
intersection 交集,显示共同存在的 >>>s1={"alex","eric","tony","李泉","李泉11"} >>>s2={"alex","eric","tony","刘一"} >>>v = s1.intersection(s2) >>>print(v) {'alex', 'eric', 'tony'} difference 差集 显示某1个不同 >>>s1={"alex","eric","tony","李泉","李泉11"} >>>s2={"alex","eric","tony","刘一"} >>>v=s1.difference(s2) #查看s2中不存在的 >>>print(v) {'李泉', '李泉11'} symmetric_difference 差集 显示2个不同 >>>s1={"alex","eric","tony","李泉","李泉11"} >>>s2={"alex","eric","tony","刘一"} >>>v=s1.symmetric_difference(s2) #不显示s1和s2中共有的元素 >>>print(v) {'李泉', '李泉11', '刘一'} union 并集 >>>s1={"alex","eric","tony","李泉","李泉11"} >>>s2={"alex","eric","tony","刘一"} >>>v=s1.union(s2) #显示s1和s2内的所有元素,重复的不显示 >>>print(v) {'李泉11', 'tony', '刘一', 'eric', '李泉', 'alex'} difference_update 赋值 >>>s1={"alex","eric","tony","李泉","李泉11"} >>>s2={"alex","eric","tony","刘一"} >>>s1.difference_update(s2) #赋值,清空s1中s2存在的元素 >>>print(s1) {'李泉', '李泉11'} discard 删除 >>>s1={"alex","eric","tony","李泉","李泉11"} >>>s1.discard("alex") #删除指定元素 >>>print(s1) {'tony', 'eric', '李泉', '李泉11'} update 增加 s1={"alex","eric","tony","李泉","李泉11"} s1.update({"aa","alex"}) #增加aa,#alex已存在不增加 print(s1) {'李泉', 'alex', 'tony', 'aa', 'eric', '李泉11' set不显示重复出现的元素 >>>s2 = set(["alex","eric","tony","eric","alex",]) #不显示重复的元素 #无序 >>>print(s2) {'eric', 'alex', 'tony'} >>>s11={1,2,3,4,5,1,2,3,4} >>>print(s11) {1, 2, 3, 4, 5} difference 原set不变,新生成的去掉指定元素, >>>s2 = set(["alex","eric","tony","eric","alex",]) #不显示重复的元素 #无序 s3= s2.difference(["alex","eric"]) #s3中去掉alex和eric元素,生成新s3无序集合 >>>print(s2) {'eric', 'alex', 'tony'} >>>print(s3) {'tony'} difference_update 原set中删除指定元素,新生成的set元素为None, >>>s2 = set(["alex","eric","tony","eric","alex",]) #不显示重复的元素 #无序 >>>s4 =s2.difference_update(["alex","eric"]) #在s2中去掉alex和eric 改变s2无序集合的元素, >>>print(s2) {'tony'} >>>print(s4) None
collections计数器
>>> import collections #定义变量 >>> obj=collections.Counter(["aa","ww","aa","adfasfqrwfafd"]) #记录元素出现的次数 >>> print(obj) Counter({'aa': 2, 'ww': 1, 'adfasfqrwfafd': 1}) >>> obj.update(["eric","11","11","aa"]) #相加,元素存在的相加元素出现的次数,不存在的元素显示出现的次数 >>> print(obj) Counter({'aa': 3, '11': 2, 'ww': 1, 'adfasfqrwfafd': 1, 'eric': 1}) >>> obj.subtract(["eric","11","12"]) 相减,元素存在的相减元素出现的次数,不存在的元素显示负数元素的次数 >>> print(obj) Counter({'aa': 3, 'ww': 1, 'adfasfqrwfafd': 1, '11': 1, 'eric': 0, '12': -1}) >>> ret=obj.most_common(2) #显示2个出现最多次数的元素 >>> print(ret) [('aa', 3), ('11', 2)] >>>for k in obj.elements(): #显示所有key >>>for k,v in obj.items(): #显示所有key和value
有序字典
>>> import collections #定义变量 >>> dic= collections.OrderedDict() #按顺序增加key和value >>> dic["k1"]="v1" >>> dic["k2"]="v2" >>> dic["k3"]="v3" >>> print(dic) OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3')]) >>> dic.move_to_end("k1") #k1顺序改到最后 >>> print(dic) OrderedDict([('k2', 'v2'), ('k3', 'v3'), ('k1', 'v1')]) >>> dic.popitem() #去掉最后一个元素 ('k1', 'v1') >>> print(dic) OrderedDict([('k2', 'v2'), ('k3', 'v3')]) >>> dic.pop("k1") #去掉指定元素 'v1' >>> print(dic) OrderedDict([('k2', 'v2'), ('k3', 'v3')]) >>>ret=(dic.pop("k3")) #pop不只是去掉k3,还可以变成其他变量 >>>print(ret) v3 >>>dic.update({"k1":"111","k2":"222","aa":"2112"}) #更新,原元素更改.新元素增加 >>>print(dic) OrderedDict([('k1', '111'), ('k2', '222'), ('k3', 'v3'), ('aa', '2112')])
默认字典
>>>import collections #定义变量 >>>dic = collections.defaultdict(list) #给dic设置默认值 >>>dic["k1"].append("alex") #dic中k1的默认值是alex >>>print(dic) defaultdict(<class 'list'>, {'k1': ['alex']})