Check if a string is palindrome using Python
-
A palindrome is a word, number or a phrase which is same when read from left to right or right to left.
Examples:
Rotor, Ava, Salas
top spot
1001, 12321, 111In this topic, we will write some sample code snippets to check if a given string is palindrome.
We can do this check in multiple ways. Here we will consider the two simplest options.
-
By comparing each character
First we need to find the half length of the string. If the length of the string is an odd number, we can skip the middle character. Then using a for loop, compare first and last characters of the string.
For each increment, next character from start and previous character from end is compared. If all the comparisons matches, string is a palindrome, otherwise not.
Copieddef checkPalindrome(strtoCheck): str1 = strtoCheck.lower().replace(" ", "") halfLen = len(str1)// 2 isPalindrome = True #Check if character matches. From start and end position for i in range(halfLen): if(str1[i] != str1[(len(str1)-1) - i]): isPalindrome = False break if(isPalindrome == True): print("'" + strtoCheck + "' is a palindrome") else: print("'" + strtoCheck + "' is not a palindrome") checkPalindrome('Rotor') checkPalindrome('Test tset') checkPalindrome('Test')
'Rotor' is a palindrome
'Test tset' is a palindrome
'Test' is not a palindrome -
By splitting the string by half and compare
Here we don't have to use a loop to do the check. Find the half length of the string and split it into two. If the length of the string is an odd number, we can skip the middle character.
Then reverse the second half string and do a comparison. If both are equal, given string is a palindrome.
Copieddef checkPalindrome(strtoCheck): str1 = strtoCheck.lower().replace(" ", "") halfLen = len(str1)// 2 firsthalf = '' secondhalf = '' if(len(str1) % 2 == 0):#Even firsthalf = str1[:halfLen] secondhalf = str1[halfLen:] else:#Odd firsthalf = str1[:halfLen] secondhalf = str1[halfLen+1:] #Compare frst half of the string with reversed second half if(firsthalf == secondhalf[::-1]): print("'" + strtoCheck + "' is a palindrome") else: print("'" + strtoCheck + "' is not a palindrome") checkPalindrome('Salas') checkPalindrome('Test')
'Salas' is a palindrome
'Test' is not a palindrome