字符串索引与切片:切片后组成新字符串与原字符串无关系
增:str1+str2
查:str1[index] str1[start_index:end_index]
1,索引从0开始
2,根据索引获取元素:索引超过字符串长度时报错
s[0]--0标识索引值
s1 = 'python is good' s2 = s1[0] print(s2)
3,切片:顾头不顾尾-后面的数字表示的位数取不到
s[0:2]--0表示起始位置,2表示结束位置
s1 = 'python is good' s2 = s1[0:2] print(s2)
4,反向计数:
s[-1]--取最后一位
s1 = 'python is good' s2 = s1[-1] print(s2)
s1 = 'python is good' s2 = s1[-2:-1] print(s2)
5,取所有元素:
s[0:]--最后一位不填写
s1 = 'python is good' s2 = s1[0:] print(s2)
6,等间隔取值:
s[0:5:2]--0:5表示取值索引范围,2表示步长-间隔1位,间隔多少位
s1 = 'python is good' s2 = s1[0:5:2] print(s2)
s[5:0:-2]--同理,-2表示反向取值
s1 = 'python is good' s2 = s1[5:0:-2] print(s2)
s[5::-2]
s[-1::-2]
s1 = 'python is good' s2 = s1[-1::-2] print(s2)
s[::-2]