数据容器
数据容器
1.
list 列表[]
''' 字符串 split后成为列表 对列表list做倒叙的[::-1] ''' #定义方法获取 列表 指定下标的 list_name=[0,1,2,3,4,5] list_name2=[-4,-3,-2,-1] list_name3="abcd,efg" def get_new(): #列表下标从1开始到3结束 左开右关 str_new=list_name[1:3] print(f"新的字符串:{str_new}") # 列表下标从1开始到3结束 左开右关 str_new2 = list_name2[-1:-4:-1] print(f"新的字符串:{str_new2}") # 难点截取split 从字符串变成列表, 并倒叙 仅列表可以倒叙 str_new3 = list_name3.split(",")[0][::-1] print(f"新的字符串:{str_new3}") #调用方法 get_new()
2.
tuple 元祖()
3.
str 字符串 "" 数据容器的切片
''' 字符串 只读 不可修改;如果非要修改需要更改类型为列表[],然后将列表再改回字符串 ''' #定义方法 def get_str(): str1="fqs" print(f"第二个字母是{str1[1]}") print(f"最后一个字母是{str1[-1]}") #1 更改字符串内的值 会报错 因为字符串类型不能被修改 #2 解决办法 引入新的列表,将字符串转列表类型 l = [] l=list(str1[1]) #3.将列表更改为字符串 ,获得新的字符串 str1=str(l) print(f"新的字符串{str1}") #调用方法 get_str()
第二个字母是q
最后一个字母是s
新的字符串['q']
''' 字符串 获取 指定元素的下标index ''' #定义方法 def get_index(): str1="fqs" #index 方法 index_value=str1.index("s") print(f"s的下标是{index_value}") #调用方法 get_index()
s的下标是2
''' 字符串 替换("旧老婆","新老婆") replace ''' #定义方法 def get_replace(): str_name="fqs" #replace 方法 new_str_name=str_name.replace("f","doudou") print(f"被替换后的new_str_name:{new_str_name}") #调用方法 get_replace()
被替换后的new_str_name:doudouqs
''' 字符串 分割字符串 split ''' #定义方法 def get_fen_duan(): str_name="f q s" #split 方法 以空格分割 new_str_name=str_name.split(" ") print(f"被替换后的new_str_name:{new_str_name}") #调用方法 get_fen_duan()
被替换后的new_str_name:['f', 'q', 's']
''' 字符串 分割字符串 strip() 1.去掉前后空格 2.去掉前后的指定字符 ''' #定义方法 def get_qu_chu_kong_ge(): str_name1=" q s豆鸭子 " # strip 方法1 去除前后空格符 new_str_name1 = str_name1.strip() print(f"去除指定元素q后的new_str_name1:{new_str_name1}") str_name2 = "12 q s豆鸭子1221" # strip 方法2 去除指定字符 new_str_name2 = str_name2.strip("12") print(f"去除指定元素q后的new_str_name2:{new_str_name2}") #调用方法 get_qu_chu_kong_ge()
''' 字符串 count 某个元素合计出现次数 ''' #定义方法 str_name="fqsfqsfqs" def get_count(): count=str_name.count("f") print(f"合计{count}个f") #调用方法 get_count()
''' 字符串 len 字符串长度 ''' #定义方法 str_name="fqsfqsfqs" def get_len(): count=len(str_name) print(f"合计{count}个f") #调用方法 get_len()
''' 字符串 "h h h h h hahahah" 1.统计有几个ha字符 字符串.count("目标") 2.将字符串内的空格全部替换为"|" 字符串.replace("|") 3.将"|"进行字符串分割,得到列表 字符串.splite("|") ''' #定义方法 str_name="h h h h h hahahah" def get_count(): count=str_name.count("ha") print(f"合计{count}个ha") #调用方法 get_count() #定义方法replace str_name2="h h h h h hahahah" def get_replace(): new_str=str_name2.replace(" ","|") print(f"最新的字符串是{new_str}") #调用方法 get_replace() #调用方法 从字符串变成列表 str_name3="h|h|h|h|h|hahahah" def get_splite(): new_list=str_name3.split("|") print(f"截取后的字符串{new_list}") get_splite()
合计3个ha
最新的字符串是h|h|h|h|h|hahahah
截取后的字符串['h', 'h', 'h', 'h', 'h', 'hahahah']
4.
set 集合
5.
dict 字典 {} 映射
浙公网安备 33010602011771号