extended slicing and negative stop value problem

Chris Angelico rosuav at gmail.com
Sat Aug 20 21:53:53 CEST 2011

On Sat, Aug 20, 2011 at 7:52 PM, Max <maxmoroz at gmail.com> wrote:
> 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".

Right, which is what I meant by setting it to an explicit None:

if input[starting_pos:ending_pos+1] == input[ending_pos :
starting_pos-1 if starting_pos >= 0 else None : -1]:

You're right that it starts to get ugly, though.

Of course, there are other ways to find the longest palindromic
substring in a string:

# I wouldn't bother counting a one-character "palindrome"
for substr_length in range(len(input),1,-1):
   for starting_pos in range(len(input)-substr_length+1):
       ending_pos = starting_pos + substr_length - 1
       testme = input[starting_pos:ending_pos+1]
       if testme == testme[::-1]:

That is, snip out the string and then reverse that snipped piece,
rather than reverse-slicing from the original. This doesn't solve the
issue of slicing backwards with variable halts, though.


More information about the Python-list mailing list