Q:

Python program to check if a string is palindrome or not

belongs to collection: Python String Programs

0

What is palindrome string?

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.

In the below program, we are implementing a python program to check whether a string is a palindrome or not?

Steps:

  • 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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Method 1: Manual

# 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

Method 2: 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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to input a string and find total nu... >>
<< Capitalizes the first letter of each word in a str...