本节内容
- 列表、元组操作
- 字符串操作
- 字典操作
- 集合操作
- 文件操作
- 字符编码与转码
names = ["a","b","c","d","e","f"] names.append('gushiren') #添加 names.insert(2,'kilo') #从b后面插入 names.insert(5,'juno') #从e后面插入 names[2] = 'icehouse' #修改del names[2] #删除 names.remove('kilo') #删除指定元素 names.pop() #删除最后一个元素 b = [1,2,3] names.extend(b) #拓展
names.count("juno") #统计
names.sort() #排序 names.reverse() #翻转names.index('kilo') #获取下标
#切片,取多个元素
>>> names = ["a","b","c","d","e","f"]
>>> names[1:4] #取下标1至下标4之间的数字,包括1,不包括4
['b', 'c', 'd']
>>> names[1:-1] #取下标1至-1的值,不包括-1
['b', 'c', 'd', 'e']
>>> names[0:3]
['a', 'b', 'c']
>>> names[:3] #如果是从头开始取,0可以忽略,跟上句效果一样
['a', 'b', 'c']
>>> names[3:] #如果想取最后一个,必须不能写-1,只能这么写
['d', 'e', 'f']
>>> names[3:-1] #这样-1就不会被包含了
['d', 'e']
>>> names[0::2] #后面的2是代表,每隔一个元素,就取一个
['a', 'c', 'e']
>>> names[::2] #和上句效果一样
['a', 'c', 'e']
元组
元组其实跟列表差不多,也是存一组数,只不是它一旦创建,便不能再修改,所以又叫只读列表
字符串操作
特性:不可修改
name.capitalize() 首字母大写 name.casefold() 大写全部变小写 name.center(50,"-") 输出 '---------------------Alex Li----------------------' name.count('lex') 统计 lex出现次数 name.encode() 将字符串编码成bytes格式 name.endswith("Li") 判断字符串是否以 Li结尾 "Alex Li".expandtabs(10) 输出'Alex Li', 将 转换成多长的空格 name.find('A') 查找A,找到返回其索引, 找不到返回-1 format : >>> msg = "my name is {}, and age is {}" >>> msg.format("alex",22) 'my name is alex, and age is 22' >>> msg = "my name is {1}, and age is {0}" >>> msg.format("alex",22) 'my name is 22, and age is alex' >>> msg = "my name is {name}, and age is {age}" >>> msg.format(age=22,name="ale") 'my name is ale, and age is 22' format_map >>> msg.format_map({'name':'alex','age':22}) 'my name is alex, and age is 22' msg.index('a') 返回a所在字符串的索引 '9aA'.isalnum() True '9'.isdigit() 是否整数 name.isnumeric name.isprintable name.isspace name.istitle name.isupper "|".join(['alex','jack','rain']) 'alex|jack|rain' maketrans >>> intab = "aeiou" #This is the string having actual characters. >>> outtab = "12345" #This is the string having corresponding mapping character >>> trantab = str.maketrans(intab, outtab) >>> >>> str = "this is string example....wow!!!" >>> str.translate(trantab) 'th3s 3s str3ng 2x1mpl2....w4w!!!' msg.partition('is') 输出 ('my name ', 'is', ' {name}, and age is {age}') >>> "alex li, chinese name is lijie".replace("li","LI",1) 'alex LI, chinese name is lijie' msg.swapcase 大小写互换 >>> msg.zfill(40) '00000my name is {name}, and age is {age}' >>> n4.ljust(40,"-") 'Hello 2orld-----------------------------' >>> n4.rjust(40,"-") '-----------------------------Hello 2orld' >>> b="ddefdsdff_哈哈" >>> b.isidentifier() #检测一段字符串可否被当作标志符,即是否符合变量命名规则 True
字典操作
字典一种key - value 的数据类型,使用就像我们上学用的字典,通过笔划、字母来查对应页的详细内容。