Python字符串切片技巧大全

概述

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 就是一个很好的例子。它有许多结果组合可以提供,只有当我们学会应用和执行这个运算符并利用它的参数时。在需要的地方理解和应用切片,因为这种优雅的语法会产生干净和高质量的代码。

    作者:新华

    物联沃分享整理
    物联沃-IOTWORD物联网 » Python字符串切片技巧大全

    发表回复