代码之家  ›  专栏  ›  技术社区  ›  Component 10

如何以编程方式切片python字符串?

  •  1
  • Component 10  · 技术社区  · 15 年前

    希望这个问题很简单。因此,在python中,可以使用以下索引拆分字符串:

    >>> a="abcdefg"
    >>> print a[2:4]
    cd
    

    但是,如果索引是基于变量的,如何做到这一点呢?例如。

    >>> j=2
    >>> h=4
    >>> print a[j,h]
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    TypeError: string indices must be integers
    
    2 回复  |  直到 13 年前
        1
  •  3
  •   Olivier Verdier    15 年前

    除了Bakkal的答案外,以下是如何以编程方式操作切片,这有时很方便:

    a = 'abcdefg'
    j=2;h=4
    my_slice = slice(j,h) # you can pass this object around if you wish
    
    a[my_slice] # -> cd
    
        2
  •  10
  •   bakkal    15 年前

    你只要有个打字错误就行了,用 a[j:h] 而不是 a[j,h] :

    >>> a="abcdefg"
    >>> print a[2:4]
    cd
    >>> j=2
    >>> h=4
    >>> print a[j:h]
    cd
    >>>