概述
Python 引入了多种字符串操作方法,允许获取字符串子字符串。其中一个操作称为 Slice。这个运算符非常通用且语法优雅,只需几个参数,就可以从字符串中获取许多子字符串组合。Python编程中的字符串切片就是通过从“开始”索引到“停止”索引切片来从给定字符串中获取子字符串。
切片()
Python 为我们提供了一个方法 slice(),它创建了一个“slice”对象,其中包含一组“start”和“stop”索引和步长值。具体来说,参数是(开始、停止、步进)。
根据 Python 官方关于 python 字符串切片的文档: Slice 有两种不同的实现方式,即 slice 有两种重载方法,每种方法都采用两组不同的参数:
-
slice(stop) // 起始为 0 & 步长为 1
-
切片(开始、停止、步进)
- start:是必须对其执行切片操作的字符串的起始索引。它确定字符串的切片将从哪里“开始”。
- stop:是切片的停止索引,'until’必须执行哪个切片操作,即在生成子字符串时排除停止索引。
- step:这是一个可选参数,用于定义迭代列表时的步骤,即它允许我们跳过元素。
两个 slice() 实现都返回一个格式为 slice(start, stop, end) 的对象。(检查示例-1)
此返回的对象现在可用于对字符串、列表、元组、集合、字节或范围对象进行切片。
应用:
示例 1 – 使用 slice 对象获取子字符串
`s = "Welcome to scaler docs" s1 = slice(6) _# takes start as 0 automatically_ print("s1-obj:", s1) print("s1-res:", s[s1]) s2 = slice(2,8) _# using slice(start, end, step) without step_ print("s2-obj:", s2) print("s2-res:", s[s2]) s3 = slice(1, 20, 2) _# using slice(start, end, step) with step_ print("s3-obj:", s3) print("s3-res:", s[s3])`
输出
`s1-obj: slice(None, 6, None) s1-res: Welcom s2-obj: slice(2, 8, None) s2-res: lcome s3-obj: slice(1, 20, 2) S3-res: ecm osae o`
解释:
Slice() 有两个实现,一个具有单个参数,另一个具有三个参数。具有一个参数的实现将“stop”索引作为唯一且必需的参数,而具有三个参数的实现也采用“start”索引、“stop”索引和可选的“step”值。
在上面的例子中(在代码片段和输出中检查s1,s2和s3):
- **在 s1 中:**我们首先使用了 slice(),它只接受一个 ‘stop’ 参数。在输出中,我们收到的子字符串为“Welcom”,因为“start”索引自动设置为“0”,而“stop”设置为6。
- **在 s2 中:**之后,我们使用带有三个参数方法的 slice(),但选择不提供可选的“step”参数。在输出中,我们收到了一个从索引“2”到“7”的子字符串,因为我们将“start”作为“2”提供,“stop”作为“8”。
- **在 s3 中:**我们也用 ‘step’ 实现 slice()。因为我们提供的“步骤”为 2。在输出中,我们通过从索引 1 到 20 前进到每个 2 个元素来接收一个子字符串
因此,现在很明显,“step”值决定了迭代器(在形成子字符串时)将以什么值前进或递增。
**注意:**理解“停止”索引意味着它不会在“此索引”或“之后”停止此索引。执行切片时,它在此索引之前停止。而“start”索引包含在被切片的字符串中。
索引语法
切片的索引语法是 slice() 的简写或更好的替代品,因为它更容易理解和执行。这是您作为开发人员欣赏的操作和语法之一,并下意识地希望在您的代码中应用,因为它确实是一个很酷的操作!
索引语法:
字符串[start : stop : step]
因此,在这里,我们不是先创建一个切片对象,然后在字符串上实现它,而是直接使用执行相同操作的索引语法。
使用索引语法复制 Example-1:
示例 2 – 切片的索引语法
`s = "Welcome to scaler docs" print("s1", s[:6]) print("s2", s[2 : 7]) _# using indexing syntax for slice(start, end, step) without step_ print("s3", s[1 : 20 : 2]) _# using indexing syntax for slice(start, end, step)_`
输出:
`s1 Welcom s2 lcome s3 ecm osae o`
注意:
- “步长”永远不能为零。
- String[ : : ] => start = 0, stop = 字符串长度,step = 1。
- String[2 : : ] => start = 2, stop = 字符串长度, step = 1
- 字符串[ :2: ] => 开始 = 0,停止 = 2,步长 = 1
- String[:6] OR String[1:6] => 是有效的语法,因为“step”是此操作的可选参数。
Slice 是一个只需要三个参数的操作,而且可以用它做更多的事情。让我们看一些示例,这些示例将解释此运算符的多个用例。
使用负指数
“开始”和“停止”索引和步长可以分别为负值。但是负指数和负“步骤”对 Python 中的字符串切片有什么影响呢?让我们来看看。请考虑下图,该图的顶部和底部标记了一个字符串和索引。
**注意:**底部的指数表示负指数。
让我们来看看如何使用负索引获取子字符串。假设我们必须获取子字符串刻度。若:
S = 欢迎使用缩放器
使用负索引获取子字符串的语法为:S[-6 : -1] OR
sliceObject = slice(-6, -1) => S[sliceObject]
(-6 个索引从末尾指向第 6 个元素,-1 指向从末尾指向第 1 个元素)
**注意:**请参阅图 1 和示例,以了解字符索引映射。
**示例 3 –**使用负索引和负步长值获取子字符串
`s = "Welcome to scaler" _# -x means xth element from the end._ print("indexing syntax without step:", s[-16 : -4]) _# using step to fetch every 2nd character from start index until end index_ print("indexing syntax with step:", s[-16 : -4 : 2]) _# replicating above code using slice object_ sliceObj = slice(-16, -4) print("slice object without step:", s[sliceObj]) sliceObj = slice(-16, -4, 2) print("slice object with step:", s[sliceObj])`
输出:
`indexing syntax without step: elcome to sc indexing syntax with step: ecm os slice object without step: elcome to sc slice object with step: ecm os`
**示例 4 –**正负指数切片
`s = "Welcome to scaler" s1 = s[3 : -7] print("positive start index, negative end index:", s1) _# above slice operation can also be written as_ s2 = s[-14 : 10] print("negative start index, positive end index:", s2)`
输出:
`positive start index, negative end index: come to negative start index, positive end index: come to`
在切片中使用负“步长”反转子字符串
Python 中的字符串切片可以通过多种方式反转字符串。切片是允许我们反转字符串的方法之一。反转字符串时,将“Step”参数视为小于 0。
**注意:**倒车时:“step”< 0,slice(start, stop, step)中的“start”>“stop”。而当不反转时:当“step”> 0 时,startIndex < slice(start, stop, step) 中的 stopIndex
让我们看一下如何使用切片进行反转的多个示例:
**示例 5 –**使用负步长反转子字符串
`s = "welcome to scaler" _# reversing complete string_ s1 = s[::-1] print("s1:", s1) _# reversing complete string by stepping to every 2nd element_ s2 = s[::-2] print("s2:", s2) _# reversing from 10th index until start, 'stop' index here automatically will be till starting of the string_ s3 = s[10::-1] print("s3:", s3) _# reversing from end until 10th index, 'start' index will automatically be the first element_ s4 = s[:10:-1] print("s4:", s4) _# reversing from 16th index till 10th index_ s5 = s[16:10:-1] print("s5:", s5) _# this will return empty, as we're not reversing here. But NOTE that this 'start' cannot be greater than ‘stop’ until & unless we're reversing_ s6 = s[11:2] print("s6:", s6) _# reversing from 14th index from the end until 4th index from the end._ s7 = s[-4:-14:-1] print("s7:", s7)`
输出:
`s1: relacs ot emoclew s2: rlc teolw s3: ot emolew s4: relacs s5: relacs s6: s7: acs ot emo`
对列表和元组进行切片操作
“slice”操作在列表和元组上的工作方式类似于它处理字符串的方式。String 是字符的顺序集合,其中每个字符都有一个类似的索引;“列表”或“元组”是任何特定类型数据的有序集合。无论哪种方式,都可以对任何有序的元素集合执行切片。
让我们看一些关于切片集和元组的示例,分别用于获取子列表和子元组。
请看下图:
**注意:**请参考图 2 来理解示例 6 和示例 7 中代码片段中的索引元素映射。
**示例 6 –**对列表执行切片操作以提取子列表
`tempList = ["Welcome", "to", "scaler", "docs.", "Have", "a", "great", "day"] _# fetching complete list_ list1 = tempList[::] print("list1:", list1) _# fetching list from 0th index to 6th index_ list2 = tempList[0 : 6] print("list2:", list2) _# jumping every third element from start to end_ list3 = tempList[:: 3] print("list3:", list3) _# jumping to every 2nd element starting from 1st index until 5th index_ list4 = tempList[1:5:2] print("list4:", list4) _# 8th index from end to 5th index from end_ list5 = tempList[-8:-5] print("list5:", list5) _# jumping every 3rd element in reverse_ list6 = tempList[::-3] print("list6:", list6) _# alternate implementation of list4_ list7 = tempList[-7:-3:2] print("list7:", list7)`
输出:
`list1: ['Welcome', 'to', 'scaler', 'docs.', 'Have', 'a', 'great', 'day'] list2: ['welcome', 'to', 'scaler', 'docs.', 'Have', 'a'] list3: ['Welcome', 'docs.', 'great'] list4: ['to', 'docs.'] list5: ['Welcome', 'to', 'scaler'] list6: ['day', 'Have', 'to'] list7: ['to', 'docs.']`
**示例 7 –**对元组执行切片操作以获取子元组
`temptuple = ("Welcome", "to", "scaler", "docs.", "Have", "a", "great", "day") tuple1 = temptuple[::] _# fetching complete tuple_ print("tuple1:", tuple1) tuple2 = temptuple[0 : 6] _# fetching tuple from 0th index to 6th index_ print("tuple2:", tuple2) tuple3 = temptuple[:: 3] _# jumping every third element from start to end_ print("tuple3:", tuple3) tuple4 = temptuple[1:5:2] _# jumping to every 2nd element starting from 1st index until 5th index_ print("tuple4:", tuple4) tuple5 = temptuple[-8:-5] _# 8th index from end to 5th index from end_ print("tuple5:", tuple5) tuple6 = temptuple[::-3] _# jumping every 3rd element in reverse_ print("tuple6:", tuple6) tuple7 = temptuple[-7:-3:2] _# alternate implementation of tuple4_ print("tuple7:", tuple7)`
输出:
`tuple1: ('Welcome', 'to', 'scaler', 'docs.', 'Have', 'a', 'great', 'day') tuple2: ('Welcome', 'to', 'scaler', 'docs.', 'Have', 'a') tuple3: ('Welcome', 'docs.', 'great') tuple4: ('to', 'docs.') tuple5: ('Welcome', 'to', 'scaler') tuple6: ('day', 'Have', 'to') tuple7: ('to', 'docs.')`
很明显,切片操作对集合的元素进行切片。这里的集合可以看作是形成字符串的字符序列,或者是元素列表或元素元组。无论订购的集合包含什么,您都可以对此类集合执行切片以获取子集合。
结论
让我们回顾一下 Python 中的字符串切片是什么:
- Slice() 是一个非常通用的操作,在从集合中获取子集合时,它提供了许多组合。
- Slice 有两种不同的语法:
- 一个创建 slice() 对象的地方,即 slice(stop) 或 slice(start, stop, step)。
- 另一个是速记属性,即 String[start:stop],它更易于使用和执行。
- “Start”确定切片操作将从中开始的索引。
- “停止”确定要执行切片的索引。要考虑“停止”指数之前的元素。
- “步骤”定义了迭代列表时的步骤,即它允许我们跳过元素。
- 索引和步长可以为负值。
如果我们打个比方,Python 中的字符串切片与现实世界中切片一条实际的面包没有什么不同。这和手术的感觉是一样的。不是吗?
Python 为我们提供了多个语法上可读且优雅的运算符和方法,slice 就是一个很好的例子。它有许多结果组合可以提供,只有当我们学会应用和执行这个运算符并利用它的参数时。在需要的地方理解和应用切片,因为这种优雅的语法会产生干净和高质量的代码。
总结
😝除了上面分享,我也给大家整理了Python学习籽料。Python+pycharm安装包,如果有需要的话,可以V扫描下方二维码联系领取哦~
学好 Python 不论是就业还是做副业赚钱都不错,但要学会 Python 还是要有一个学习规划。最后大家分享一份全套的 Python 学习资料,给那些想学习 Python 的小伙伴们一点帮助!
因篇幅有限,仅展示部分资料,添加上方即可获取👆