Search code examples
pythonstringindices

Why does not the negative indices in python strings result as expected?


I created a string in python : 'HelpA' and labeled it as word.

>>>word='HelpA'

>>>word

'HelpA' #expected string

>>>word[0:4]

'Help' #expected string

While calling the word with negative indices, I am getting the full string instead of partial string as expected.

>>>word[-97:]

'HelpA'  #not the expected string

Its giving the whole string instead of expected string : 'pA' Why does this happen?


Solution

  • It seems like you expect the negative index to 'wrap'. (97 % len(word) == 2).

    It doesn't :)

    This example shows you why:

    >>> word[-1:]
    'A'
    >>> word[-3:]
    'lpA'
    >>> word[-5:]
    'HelpA'
    >>> word[-10:]
    'HelpA'
    

    When the negative index goes beyond the length of the string, it will be truncated. This section of the Python documentation explains explains it like this:

    The slice of s from i to j is defined as the sequence of items with index k such that i <= k < j

    This code does the equivalent slicing (for strings):

    def slice(s, i, j):
        sliced = []
        for k, item in enumerate(s):
            if i <= k and k < j:
                sliced.append(item)
        return ''.join(sliced)
    

    Output:

    >>> slice('foo', -100, 2)
    'fo'
    >>> 'foo'[-100:2]
    'fo'
    

    This should make it clear why word[-100:] and word[-99:] gives the same result: all characters in the string have a position or index larger than -100 or -99, since 0 is the first position of the string