Python 之string

代码
>>> # Replace some items:
... a[0:2= [112]
>>> a
[
1121231234]
>>> # Remove some:
... a[0:2= []
>>> a
[
1231234]
>>> # Insert some:
... a[1:1= ['bletch''xyzzy']
>>> a
[
123'bletch''xyzzy'1234]
>>> # Insert (a copy of) itself at the beginning
>>> a[:0] = a
>>> a
[
123'bletch''xyzzy'1234123'bletch''xyzzy'1234]
>>> # Clear the list: replace all items with an empty list
>>> a[:] = []
>>> a
[]


切片

   当使用Python扩展的切片语法时,就会创建切片对象。
      步进切片、多维切片和省略切片
      步进切片:sequence[起始索引:结束索引:步进值]
       多维切片语法是sequence[start1:end1,start2:end2],或者使用省略号,sequence[...,start1:end1]
      切片对象也可以由内建函数slice()生成。
      切片属于序列操作符([],[:])

Example

代码
>>> MyTestPython="123456789"
>>> MyTestPython[0]
84'1'
>>> MyTestPython[2]
85'3'
>>> MyTestPython[1,2]
>>> MyTestPython[1:3#这里是从下标为1开始,到下标为3结束的切片
86'23'
# | +1+ | +2+ | +3+ | +4+ | +5+ | +6+ | +7+ | +8+ | +9+ |    #
#
 0       1        2        3       4        5        6        7       8       9  #
#
-9       -8      -7      -6      -5       -4       -3      -2      -1          #
>>> 


从上面的方式可以看到切片的方式。

 步进切片实例
>>>foostr = 'abcde'
>>>foostr[ : : -1]
'edcba'
>>>foostr[: : -2]
'eca'
>>>foolist = [123, 'xba', 423.535, 'adsf']
>>>foolist [: : -1]
['adsf', 423.535, 'xba', 123]

原文地址:https://www.cnblogs.com/65702708/p/1707573.html