Question
Write a python program to check whether given string is palindrome or not without using any inbuilt function to reverse the string
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# Program to check if a string is palindrome or not take input from the user string = raw_input("Enter a string: ") #Use inbuilt function to convert all characters to lowercase string = string.lower() # check if the string is equal to its reverse if string == string[::-1]: print("It is palindrome") else: print("It is not palindrome") |
Explanation:
A palindrome is a string which is same read forward or backwards. Dad is a palindrome while Python is not.
In the program, we first accept the string to ‘string’. Since capital letters and small letters are perceived differently because of difference in ASCII codes, we convert the string to all lower for uniformity using inbuilt function ‘x.lower()’ where x is the string
In the above program, we have used the slice operator to reverese the string.The slice operator[n:m:p] returns the part of the string from nth to the (m-1)th character Setting p to -1 returns the reverse order of the slice of string you asked for. Since here we want the whole string, we use the shorthand [::-1]
Compare both the string and it’s reversal. If they are equal, then it’s a palindrome, otherwise not.
Output:
1.
1 2 3 |
Enter a string: Dad It is palindrome |
1 2 3 |
Enter a string: Python It is not palindrome |
Leave a Reply