Check if suffix and prefix of a string are palindromes in Python

Suppose we have a string s, we have to check whether the string palindromes as its prefix and suffix substrings or not.

So, if the input is like s = "levelishighforracecar", then the output will be True as there are palindrome prefix and suffix: "level" and "racecar" respectively.

To solve this, we will follow these steps −

  • l := size of s
  • for i in range 2 to l + 2, do
    • if substring of s up to index i is palindrome, then
      • come out from loop
    • if i is same as(l + 1) , then
      • return False
    • for i in range 2 to l + 2, do
      • if substring of s from index (l - i) to (l - 1) is palindrome, then
        • return True
    • return False

Let us see the following implementation to get better understanding −

Example Code

Live Demo

def is_palindrome(s):
   return s == s[::-1]  
def solve(s):
   l = len(s)
   for i in range(2, l + 1):
      if is_palindrome(s[0:i]):
   if i == (l + 1):
      return False
   for i in range(2, l + 1):
      if is_palindrome(s[l - i : l]):
         return True
   return False  

s = "levelishighforracecar"