Python3 string slice interception (summary)

Python3 string slice interception (summary)

basic concept

For example: if there is a character string abcdefg, Pythonthere will be two indexes , positive and negative, to mark it.

String a b c d e f g
Positive index 0 1 2 3 4 5 6
Reverse index -7 -6 -5 -4 -3 -2 -1

Positive index: From left to right, the index of the first element is 0ascending to the right.
Inverse index: From right to left, the subscript of the last element is -1in descending order to the left.

Code practice

>>> ss='abcdefg'  # 测试字符串

>>> ss[0:3]  # 左闭右开,从下标为0 的元素截取到下标为3 之前的元素(不包括下标为3 的元素)
'abc'

>>> ss[-7:-4]  # 使用逆索引,参照上表截取出同样的字符串
'abc'

>>> ss[2:]  # 省略冒号后面的数字,这里表示从下标为2 的元素开始截取到字符串结束
'cdefg'

>>> ss[:5]  # 省略冒号前面的数字,这里表示从字符串开头开始截取到下标为5 之前的元素
'abcde'

>>> ss[::2]  # 方括号第三个数字表步长,默认为1,这里从字符串开始到结束每2 个下标即每隔一个元素提取一个字符
'aceg'

# 注意:当步长为负数时,字符串遍历的指针变成从右向左迭代,所以数值大的下标要写在第一个冒号的左边
>>> ss[6:0:-1]
'gfedcb'
>>> ss[-1:-7:-1]  # 使用逆序的索引也是可以的,左闭右开的原因,这里-7 下标的元素是取不到的
'gfedcb'
>>> ss[-1:-8:-1]  # 如果想取到完整的反转字符串可以用逆序索引,并将最小索引值-1
'gfedcba'
>>> ss[6:0:-1]  # 用正序索引是取不到完整的反转字符串的,以为冒号右边的0 不取,-1 代表着最后一个元素
'gfedcb'
>>> ss[6:-1:-1] # 这样用相当于从字符g 开始取到g 右边的元素,所以结果是空
''

# 当字符串截取出来后还可以用下一个方括号进行截取
>>> ss[1:3][::-1]  # 截取下标为1 到下标为3 之前的字符串,并将其反转
'cb'

Article reference

How To Index and Slice Strings in Python 3

Published 27 original articles · praised 4 · visits 9692

Guess you like

Origin blog.csdn.net/yoshubom/article/details/104226787