序列
序列是指:内容续、有序,可以使用下标索引的一类数据容器
序列的常用操作:切片
对list进行切片,从1开始,4结束,步长1
my_list = [0, 1, 2, 3, 4, 5, 6]
result1 = my_list[1:4] # 步长默认是1,所以可以省略不写
print(f"结果1:{result1}")
结果:
结果1:[1, 2, 3]
对列表进行切片,从3开始,到1结束,步长-1
my_list = [0, 1, 2, 3, 4, 5, 6]
result2 = my_list[3:1:-1]
print(f"结果2:{result2}")
结果:
结果2:[3, 2]
对tuple进行切片,从头开始,到最后结束,步长1
my_tuple = (0, 1, 2, 3, 4, 5, 6)
result3 = my_tuple[:] # 起始和结束不写表示从头到尾,步长为1可以省略
print(f"结果3:{result3}")
结果:
结果3:(0, 1, 2, 3, 4, 5, 6)
对元组进行切片,从头开始,到尾结束,步长-2
my_tuple = (0, 1, 2, 3, 4, 5, 6)
result4 = my_tuple[::-2]
print(f"结果4:{result4}")
结果:
结果4:(6, 4, 2, 0)
对str进行切片,从头开始,到最后结束,步长2
my_str = "0123456"
result5 = my_str[::2] # 起始和结束不写表示从头到尾,步长为2为:2
print(f"结果5:{result5}")
结果5:0246
对str进行切片,从头开始,到最后结束,步长-1
my_str = "0123456"
result6 = my_str[::-1]
print(f"结果6:{result6}")
结果:
结果6:6543210
练习:
# 定义字符串:"万过薪月,员序程马黑来,nohtyp学"
my_str = "万过薪月,员序程马黑来,nohtyp学"
new_my_str = my_str[::-1]
print(f"先把字符串:{my_str},倒序得到新字符串:{new_my_str}")
# 方法1
new_my_str1 = new_my_str[9:15]
print(f"将字符串:{new_my_str}切片得到字符串:{new_my_str1}")
print("----------------------------------")
# 方法二
new_my_str1 = new_my_str.replace("来", " ")
my_list = new_my_str1.split(",")
print(f"将字符串:{new_my_str}中的'来'替换为'空格'得到:{new_my_str1},它的格式是{type(new_my_str1)}")
print(f"将字符串:{new_my_str1}根据','切割得到:{my_list},它的格式是{type(my_list)}\n{my_list[1]}")
结果:
先把字符串:万过薪月,员序程马黑来,nohtyp学,倒序得到新字符串:学python,来黑马程序员,月薪过万
将字符串:学python,来黑马程序员,月薪过万切片得到字符串:黑马程序员,
----------------------------------
将字符串:学python,来黑马程序员,月薪过万中的'来'替换为'空格'得到:学python, 黑马程序员,月薪过万,它的格式是<class 'str'>
将字符串:学python, 黑马程序员,月薪过万根据','切割得到:['学python', ' 黑马程序员', '月薪过万'],它的格式是<class 'list'>
黑马程序员