-9

What does this kind of indexing refer to in case of recursion.

def is_palindrome(s):
if len(s) < 1:
    return True
else:
    if s[0] == s[-1]:
        return is_palindrome(s[1:-1])
    else:
        return False

a=str(input("Enter string:"))
if(is_palindrome(a)==True):
    print("String is a palindrome!")
else:
    print("String isn't a palindrome!")
Clément
  • 1,128
  • 7
  • 21
SahilTyagi
  • 27
  • 1
  • 1
  • 8
  • 2
    It's fairly obvious if you try looking at the result: `"abcde"[1:-1] == "bcd"`. – chepner Dec 18 '19 at 14:59
  • Have you tried a simpler example, say `"hello"[1:-1]`? – Nils Werner Dec 18 '19 at 14:59
  • 1
    Sounds like you need to learn about [slicing](https://www.pythoncentral.io/cutting-and-slicing-strings-in-python/) in python – Dan Dec 18 '19 at 15:00
  • 1
    Please don't post images of code or data. ... [Why not upload images of code on SO when asking a question?](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-on-so-when-asking-a-question) ... [You should not post code as an image because:...](https://meta.stackoverflow.com/a/285557/2823755) – wwii Dec 18 '19 at 15:04

1 Answers1

2

If you look in the documentation, this expression is called slicing : Python: Slicing

You can add three arguments in this syntax.

The first is the start of the sequence, the second is the end (not included) and the third is the step.

When you put a negativ arguments it means that you count from the end of your array.

So for :

s = "Hello World"
s = s[1:-1]

You would have :

s = "ello Worl"

For your case it is recursive to go step by step to the center of the string and each time you check if the string is still a palindrome. When you have only one character or less it returns True because everything before was OK to say that your string is a palindrome

Clément
  • 1,128
  • 7
  • 21