extended slicing and negative stop value problem

Max maxmoroz at gmail.com
Sat Aug 20 14:52:20 EDT 2011


On Aug 20, 11:29 am, Chris Angelico <ros... at gmail.com> wrote:
> If you're using a variable for the stop value, you just need to set it
> to an explicit None if it would fall negative:
>
> >>> a[10:None:-1]
>

That doesn't work if it's set in a loop or if it's calculated as a
formula. For example, this very simple code doesn't work because of
the "-1 problem".

# find the longest substring that reads the same left to right and
right to left
for substr_length in range(len(input),0,-1):
    for starting_pos in range(len(input)-substr_length+1):
        ending_pos = starting_pos + substr_length - 1
        if input[starting_pos:ending_pos+1] == input[ending_pos :
starting_pos-1 : -1]:
           print(input[starting_pos:ending_pos+1])
           exit(0)

Of course you can rewrite it, but it becomes quite ugly.

(Not to mention, people who learn the language would not always know
this, and will end up with a bug.)




More information about the Python-list mailing list