数据类型及常用方法
一、字符串
1.说明
(1)字符串需加引号;
name = "我是Allen" name = 'Allen' name = """Allen""" name = '''我是Allen'''
(2)字符串创建后不可修改,修改字符串相当于在内存中另外生成一个数据,使用该变量名;
>>>a = "allen" >>>id(a) >>>54933968 >>>a = "tsui" >>>id(a) >>>55058136
(3)字符串可被迭代;
a = "allen" for i in a:print(i)输出: a l l e n
(4)字符串索引、切片,从左到右从0开始编号,-1表示最后一个元素;
a = "allen" print(a[0], a[3]) print(a[2:-1]) # 注意,索引是左闭区间,右开区间,所以不包含最后一个元素 输出: a e le
2.方法
(1)capitalize():首字母大写
name = "allen" v = name.capitalize() print(v)输出: Allen
(2)upper():全部变成大写
name = "allen" v = name.upper() print(v)输出: ALLEN
(3)lower():全部变成小写
name = "aLLen" v = name.lower() print(v)输出: allen
(4)center():设置宽度,并将内容居中
name = "allen" v1 = name.center(20) # 设置总长度为20,并将allen居中 v2 = name.center(20, "=") # 设置总长度为20,并将allen居中,其余使用=填充 print(v1) print(v2)输出:allen =======allen========
(5)count():字符串中寻找子序列的出现次数
name = "allenleeneeeddgendg" v = name.count("en") # 寻找en出现的次数 print(v)v = name.count("en",7,9) # 从字符串索引7到索引9(不包括9)之间寻找en出现的次数 print(v)输出: 3 1
(6)endswith():是否以···结尾
name = "allenleeneeeddgendg" v = name.endswith("d") print(v)v = name.endswith("dg") print(v)输出: False True
(7)startswith():是否以···开头
name = "allenleeneeeddgendg" v = name.startswith("a") print(v)v = name.startswith("ad") print(v)输出: True False
(8)find():从开始往后找,找到第一个子字符串后获取所在的位置,未找到显示-1
name = "allenallen" v = name.find("en") print(v)v = name.find("en", 6, 10) # 从index6开始到index10位置结局寻找 print(v)输出: 3 8
(9)index():查找子字符串后获取所在的位置,找不到报错
name = "allen" v = name.index("en") print(v)输出: 3
(10)format() / format_map():格式化,将一个字符串中的占位符替换为指定的值
test = 'i am {name}, age {a}' print(test) v = test.format(name='allen',a=19) print(v)输出: i am {name}, age {a} i am allen, age 19test = 'i am {0}, age {1}' print(test) v = test.format('allen', 19) print(v)输出: i am {0}, age {1} i am allen, age 19test = 'i am {name}, age {a}' print(test) v1 = test.format(name='allen',a=10) v2 = test.format_map({"name": 'allen', "a": 19}) print(v1) print(v2)输出: i am {name}, age {a} i am allen, age 10 i am allen, age 19
(11)isalnum():字符串中是否只包含字母和数字
a = "123" v1 = a.isalnum() b = "ddd123" v2 = b.isalnum() c = "ddd" v3 = c.isalnum() d = "$ddd" v4 = d.isalnum() print(v1, v2, v3, v4)输出: True True True False
(12)title():把所有单词第一个字母设置为大写
a = "i am allen" v = a.title() print(v)输出: I Am Allen
(13)isalpha():是否是字母
a = "12dd" v = a.isalpha() print(v)a = "dd" v = a.isalpha() print(v)输出: False True
(14)isdecimal() / isdigit() / isnumeric():是否是数字
a = "二" v1 = a.isdecimal() v2 = a.isdigit() v3 = a.isnumeric() print(v1, v2, v3)输出: False False Truea = "1" v1 = a.isdecimal() v2 = a.isdigit() v3 = a.isnumeric() print(v1, v2, v3)输出: True True Truea = "②" v1 = a.isdecimal() v2 = a.isdigit() v3 = a.isnumeric() print(v1, v2, v3)输出: False True True
(15)isprintable():是否存在不可显示的字符
a = "allen\ttsui" 存在\t、\n等转义字符 v = a.isprintable() print(v)输出: False
(16)isspace():判断是否全部是空格
a = " " v = a.isspace() print(v)输出: True
(17)istitle():判断是否是标题
a = "i am allen" v = a.istitle() print(v)a = "I Am Allen" v = a.istitle() print(v)输出: False True
(18)join():将字符串中的每一个元素按照指定分隔符进行拼接
a = "i am allen" v = "$".join(a) # 用$拼接每个元素 print(v)输出: i$ $a$m$ $a$l$l$e$n
(19)islower() / isupper():判断是否全部是大/小写
(20)strip() / lstrip() / rstrip():移除指定字符串
a = "allen" v1 = a.lstrip('a') # 从左边移除 v2 = a.rstrip('en') # 从右边移除 v3 = a.strip("allen") print(v1) print(v2) print(v3)a = " allen " v1 = a.lstrip() # 不给参数表示从左边移除空格 v2 = a.rstrip() # 不给参数表示从右边移除空格 v3 = a.strip() print(v1) print(v2) print(v3)输出: llen allallen allen allen
(21)maketrans():对应关系替换
v = "allentsui" m = str.maketrans("ati", "123") new_v = v.translate(m) print(new_v)输出: 1llen2su3
(22)partition() / rpartition():分割为三部分
a = "allentsuei" v = a.partition("e") # 从左边查找对应分割字符 print(v)输出: ('all', 'e', 'ntsuei')a = "allentsuei" v = a.rpartition("e") # 从右边查找对应分割字符 print(v)输出: ('allentsu', 'e', 'i')
(23)split() / rsplit():分割为指定个数
a = "allentesuei" v = a.split("e") # 找出全部符合字符进行分割 print(v)a = "allentesuei" v = a.split("e", 2) # 找出指定数量符合字符进行分割 print(v)a = "allentesuei" v = a.rsplit("e", 2) # 从右边开始找出指定数量符合字符进行分割 print(v)输出: ['all', 'nt', 'su', 'i'] ['all', 'nt', 'suei'] ['allent', 'su', 'i']
(24)splitlines():根据换行符分割,true/false表示是否保留换行
test = "asdfadfasdf\nasdfasdf\nadfasdf" v = test.splitlines(False) print(v)test = "asdfadfasdf\nasdfasdf\nadfasdf" v = test.splitlines(True) print(v)输出: ['asdfadfasdf', 'asdfasdf', 'adfasdf'] ['asdfadfasdf\n', 'asdfasdf\n', 'adfasdf']
(25)swapcase():大小写转换
a = "Allen" v = a.swapcase() print(v)输出: aLLEN
(26)replace():将指定字符串替换为指定字符串
a = "allenallenallen" v = a.replace("en", "us") print(v)a = "allenallenallen" v = a.replace("en", "us", 2) # 指定转换次数 print(v)输出: allusallusallus allusallusallen
(27)len():获取字符串长度
a = "allen" print(len(a))输出: 5
二、数字
1.说明
(1)无需引号;
age = 13
2.方法
(1)int():将字符串转换为数字
a = "123" print(type(a),a)b = int(a) print(type(b),b)输出: <class 'str'> 123 <class 'int'> 123
num = "0011" v1 = int(num) v = int(num, base=2) # int()默认是十进制转换,可通过base=指定进制 print(v1, v)输出: 11 3
(2)bit_length():当前数字的二进制占位长度
num = 11 v = num.bit_length() print(v)输出: 4
三、列表
1.说明
(1)使用中括号[]括起来;
(2)使用索引引用元素,下标从0开始;
a = [1, 22, "ww", "allen"] print(a[0], a[2])输出: 1 ww
(3)元素可为任何类似数据,字符串、数字、列表、元组、字典···;
(4)有序,元素可被修改;
a = [1, 22, "ww", "allen"] print(id(a))a[1] = 11 print(a) print(id(a))输出: 47484616 [1, 11, 'ww', 'allen'] 47484616
(5)元素删除方法:1、del 元素;2、pop();3、remove();4、clear()
2.方法
(1)append():原来值最后追加
a = [1, 22, "ww", "allen"] a.append("tsui") print(a)输出: [1, 22, 'ww', 'allen', 'tsui']
(2)clear():清空列表
a = [1, 22, "ww", "allen"] a.clear() print(a)输出: []
(3)copy():浅拷贝
a = [1, 22, "ww", "allen"] v = a.copy() print(a, v)输出: [1, 22, 'ww', 'allen'] [1, 22, 'ww', 'allen']
(4)count():计算元素出现的次数
a = [1, 22, "ww", "allen"] v = a.count(22) print(v)输出: 1
(5)extend():扩展原列表,参数:可迭代对象
a = [1, 22, "ww", "allen"] a.append(["aa", "bb"]) print(a) b = [1, 22, "ww", "allen"] b.extend(["aa", "bb"]) print(b)输出: [1, 22, 'ww', 'allen', ['aa', 'bb']] [1, 22, 'ww', 'allen', 'aa', 'bb']
(6)index():根据值获取当前值索引位置(左边优先)
a = [1, 22, "ww", 22, "allen"] v = a.index(22) print(v)输出: 1
(7)insert():在指定索引位置插入元素
a = [1, 22, "ww", 22, "allen"] a.insert(3, "abc") print(a)输出: [1, 22, 'ww', 'abc', 22, 'allen']
(8)pop():删除某个值(不指定索引,默认删除最后一个),并获取删除的值
a = [1, 22, "ww", 22, "allen"] v = a.pop() print(a) print(v)v = a.pop(0) print(a) print(v)输出: [1, 22, 'ww', 22] allen [22, 'ww', 22] 1
(9)remove():删除列表中的指定值,左边优先
a = [1, 22, "ww", 22, "allen"] a.remove(22) print(a)输出: [1, 'ww', 22, 'allen']
(10)reverse():将当前列表进行翻转
a = [1, 22, "ww", 22, "allen"] a.reverse() print(a)输出: ['allen', 22, 'ww', 22, 1]
四、元组
1.说明
(1)有序,一级元素不可修改,不能被增加或者删除(可转换为列表,修改完再转换会元组),元组里面的列表等可修改的元素的子元素可被修改;
tu = (1, 22, "ww", 22, "allen", [11, 22, 33]) tu[5][0] = 111 print(tu)输出: (1, 22, 'ww', 22, 'allen', [111, 22, 33])
(2)可迭代对象
2.方法
(1)count()
(2)index()
(3)join()
五、字典
1.说明
(1)大括号{}括起来的键值对,value可为任何类型的值;
(2)无序;
(3)布尔值(1,0)、列表、字典不能作为字典的key;
(4)通过key找到指定元素
2.方法
(1)dict.fromkeys():根据序列,创建字典,并指定统一的值
v = dict.fromkeys(["k1",123,"999"],123) print(v)输出: {'k1': 123, 123: 123, '999': 123}
(2)get():根据Key获取值,key不存在时,可以指定默认值(None)
dic = {"k1":"aa", "k2":"bb",} v = dic['k1'] print(v) v = dic.get('k3',"cc") print(v)输出: aa cc
(3)pop():删除并获取值
dic = {"k1":"aa", "k2":"bb",} v = dic.pop("k1") print(dic,v)输出: {'k2': 'bb'} aa
(4)setdefault():设置值,已存在,不设置,获取当前key对应的值;不存在,设置,获取当前key对应的值
dic = {"k1":"aa", "k2":"bb",} v = dic.setdefault("k1", "aaa") print(dic,v)v = dic.setdefault("k3", "ccc") print(dic,v)输出: {'k1': 'aa', 'k2': 'bb'} aa {'k1': 'aa', 'k2': 'bb', 'k3': 'ccc'} ccc
(5)update():更新
dic = {"k1":"aa", "k2":"bb",} dic.update({"k1": "aaa", "k2": "bbb"}) print(dic)dic.update(k1="aaaa", k2="bbbb", k3="cccc") print(dic)输出: {'k1': 'aaa', 'k2': 'bbb'} {'k1': 'aaaa', 'k2': 'bbbb', 'k3': 'cccc'}
六、集合
1.说明
(1)大括号{}括起来的数据集合,元素不可重复;
(2)可迭代对象
2.方法
(1)set():转换成集合
s=set('hello') print(s)输出: {'e', 'h', 'o', 'l'}
(2)add():增加元素
s={1,2,3,4,5,6} s.add("3") print(s)输出: {1, 2, 3, 4, 5, 6, '3'}
(3)clear():清空集合
s={1,2,3,4,5,6} s.clear() print(s)输出: set()
(4)copy():复制集合
(5)pop():随机删元素
(6)remove():指定删除元素,删除元素不存在会报错
s={1,2,3,4,5,6} s.remove(7) print(s)输出: KeyError: 7
(7)discard():指定删除元素,删除元素不存在不会报错
s={1,2,3,4,5,6} s.discard(7) print(s)输出: {1, 2, 3, 4, 5, 6}
(8)intersection():求交集,可用&符号代替
s1 = {1, 2, 3, 4, 5, 6, 'b', 'd'} s2 = {1, 3, 5, 'a', 'c', 'e'} print(s1.intersection(s2)) print(s1 & s2)输出: {1, 3, 5} {1, 3, 5}
(9)union():求并集,可用|符号代替
s1 = {1, 2, 3, 4, 5, 6, 'b', 'd'} s2 = {1, 3, 5, 'a', 'c', 'e'} print(s1.union(s2)) print(s1 | s2)输出: {1, 2, 3, 4, 5, 6, 'd', 'c', 'e', 'a', 'b'} {1, 2, 3, 4, 5, 6, 'd', 'c', 'e', 'a', 'b'}
(10)difference():求差集,可用-符号代替
s1 = {1, 2, 3, 4, 5, 6, 'b', 'd'} s2 = {1, 3, 5, 'a', 'c', 'e'} print(s1.difference(s2)) print(s1 - s2)print(s2.difference(s1)) print(s2 - s1)输出: {2, 'b', 4, 6, 'd'} {2, 'b', 4, 6, 'd'} {'e', 'a', 'c'} {'e', 'a', 'c'}
(11)symmetric_difference():求交叉补集,可用^符号代替
s1 = {1, 2, 3, 4, 5, 6, 'b', 'd'} s2 = {1, 3, 5, 'a', 'c', 'e'} print(s1.symmetric_difference(s2)) print(s1 ^ s2)输出: {'c', 2, 4, 6, 'e', 'd', 'a', 'b'} {'c', 2, 4, 6, 'e', 'd', 'a', 'b'}
(12)difference_update():求差集并更新
s1 = {1, 2, 3, 4, 5, 6, 'b', 'd'} s2 = {1, 3, 5, 'a', 'c', 'e'} s1.difference_update(s2) print(s1) print(s1 - s2)输出: {'b', 2, 4, 6, 'd'} {'b', 2, 4, 6, 'd'}
(13)isdisjoin():两个集合的交集是否为空
s1 = {6, 'b', 'd'} s2 = {1, 3, 5, 'a', 'c', 'e'} print(s1.isdisjoint(s2))输出: True
(14)issubset():是否子集
s1 = {6, 'b', 'd'} s2 = {6, 'b', 'd', 'c', 'e'} print(s1.issubset(s2))输出: True
(15)issuperset():是否父集
s1 = {6, 'b', 'd'} s2 = {6, 'b', 'd', 'c', 'e'} print(s1.issuperset(s2)) print(s2.issuperset(s1))输出: False True
(16)update():更新多个值
s1 = {6, 'b', 'd'} s2 = {2, 'a', 'c'} s1.update(s2) print(s1) #更新多个值 输出: {2, 'b', 6, 'a', 'c', 'd'}s1 = {6, 'b', 'd'} s1.add(1, 2, 3) print(s1) #更新一个值 输出: TypeError: add() takes exactly one argument (3 given)s1 = {6, 'b', 'd'} s2 = {2, 'a', 'c'} s1.union(s2) print(s1) #不更新 输出: {'b', 'd', 6}