
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
- if substring of s from index (l - i) to (l - 1) is palindrome, then
- return False
- if substring of s up to index i is palindrome, then
Let us see the following implementation to get better understanding −
Example Code
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]): break 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" print(solve(s))
Input
"levelishighforracecar"
Output
True
- Related Articles
- Check if a string is suffix of another in Python
- How to check if string or a substring of string ends with suffix in Python?
- Python Check if suffix matches with any string in given list?
- match_results prefix() and suffix() in C++
- Find the longest sub-string which is prefix, suffix and also present inside the string in Python
- How to check if a string ends with a specified Suffix string in Golang?
- How to check if a string starts with a specified Prefix string in Golang?
- Program to check a string can be split into three palindromes or not in Python
- How can I eradicate some specific suffix or prefix or both from a MySQL string?
- Python - Check if frequencies of all characters of a string are different
- Python - Check If All the Characters in a String Are Alphanumeric?
- Print the longest prefix of the given string which is also the suffix of the same string in C Program.
- Check if the characters of a given string are in alphabetical order in Python
- How to Add Prefix or Suffix to a Range of Cells in Excel
- Find index i such that prefix of S1 and suffix of S2 till i form a palindrome when concatenated in Python

Advertisements