字符串切片
输出结果:
val : p
字符串切片1 切出python: python
字符串切片1 切出python2: python
字符串切片1 切出python2: python
字符串切片1 切出hello: hello
字符串切片1 切出hello: hello
字符串切片1 切出hello2: hello
字符串切片1 切出: el,yh
字符串切片 text[::1]: hello,python
字符串切片 text[::2]: hlopto
字符串反转 切出: nohtyp,olleh
字符串反转 切出2: nohtyp,olleh
'''
字符串切片(字符串截取),字符串也是一个序列
语法: [start: stop: step]
1.start => 开始索引 默认:0
2.stop => 结束索引,不包括stop 默认:到最后
3.step => 步长 默认:1
三个都有默认值,但注意不能一个都不写。
text = "hello,python"
索引:
0:h
1: e
2: l
3: l
4: o
5: ,
6: p
7: y
8: t
9: h
10: o
11: n
'''
text = "hello,python"
# 根据索引取字符串中的对应该字符
print(f'val : {text[6]}')
# 指定开始索引,省略 结束索引和步长,这时结束索引为字符串最后一位,步长为1
print(f'字符串切片1 切出python: {text[6:]}')
# 指定开始索引和结束索引,省略 步长,这时 步长为1
print(f'字符串切片1 切出python2: {text[6:12]}')
# 指定开始索引和结束索引不写死用len()获取长度,省略 步长,这时 步长为1
print(f'字符串切片1 切出python2: {text[6:len(text)]}')
print(f'字符串切片1 切出hello: {text[0:5:1]}')
# 指定结束索引,省略 开始索引和步长,这时 开始索引为0, 步长为1
print(f'字符串切片1 切出hello: {text[:5:]}')
print(f'字符串切片1 切出hello2: {text[0:5:]}')
# 正常语法 指定 步长为2
print(f'字符串切片1 切出: {text[1:10:2]}')
print(f'字符串切片 text[::1]: {text[::1]}')
print(f'字符串切片 text[::2]: {text[::2]}')
# 字符串反转
print(f'字符串反转 切出: {text[::-1]}')
print(f'字符串反转 切出2: {text[-1: -len(text) - 1: -1]}')
#