Python program to check if a string is palindrome or not

Here, we are going to learn how to check whether a given string is palindrome or not in Python programming language? By IncludeHelp Last updated : February 25, 2024

A string is a palindrome if the string read from left to right is equal to the string read from right to left i.e. if the actual string is equal to the reversed string.

Problem statement

Given a string, you have to implement a python program to check whether a string is a palindrome or not?

Algorithm

Below is the algorithm (steps) to find whether given string is Palindrome or not in Python:

  • First, find the reverse string
  • Compare whether revers string is equal to the actual string
  • If both are the same, then the string is a palindrome, otherwise, the string is not a palindrome.

Example

Input: 
"Google"
Output:
"Google" is not a palindrome string

Input:
"RADAR"
Output:
"RADAR" is a palindrome string

Palindrome Check Using Manual Approach

# Python program to check if a string is 
# palindrome or not

# function to check palindrome string
def isPalindrome(string):
  result = True
  str_len = len(string)
  half_len= int(str_len/2)

  for i in range(0, half_len):
    # you need to check only half of the string
    if string[i] != string[str_len-i-1]:
      result = False
    break
  
  return result 

# Main code
x = "Google"
if isPalindrome(x):
  print(x,"is a palindrome string")
else:
  print(x,"is not a palindrome string")  

x = "ABCDCBA"
if isPalindrome(x):
  print(x,"is a palindrome string")
else:
  print(x,"is not a palindrome string")

x = "RADAR"
if isPalindrome(x):
  print(x,"is a palindrome string")
else:
  print(x,"is not a palindrome string") 

Output

Google is not a palindrome string
ABCDCBA is a palindrome string
RADAR is a palindrome string

Palindrome Check Using String Slicing

# Python program to check if a string is 
# palindrome or not

# function to check palindrome string
def isPalindrome(string):
  rev_string = string[::-1]
  return string == rev_string

# Main code
x = "Google"
if isPalindrome(x):
  print(x,"is a palindrome string")
else:
  print(x,"is not a palindrome string")  

x = "ABCDCBA"
if isPalindrome(x):
  print(x,"is a palindrome string")
else:
  print(x,"is not a palindrome string")

x = "RADAR"
if isPalindrome(x):
  print(x,"is a palindrome string")
else:
  print(x,"is not a palindrome string")  

Output

Google is not a palindrome string
ABCDCBA is a palindrome string
RADAR is a palindrome string

To understand the above programs, you should have the basic knowledge of the following Python topics:

Python String Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.