Palindrome six ways— Python Interview Problems – Interview Buddy … - MywallpapersMobi

Python Logo
• Java
• C Tutorial
• C++
• Kotlin
• Swift
• R Tutorial

search

close

# Python Program to Check Whether a String is Palindrome or Not

In this program. you’ll learn to check whether a string is palindrome or Not

To understand this example, you should have the knowledge of following Python programming topics:

• Python if…else Statement
• Python Strings
• Python String Methods

A palindrome is a string which is same read forward or backwards.

For example: "dad" is the same in forward or reverse direction. Another example is "aibohphobia" which literally means, an irritable fear of palindromes.

## Source Code

```# Program to check if a string
# is palindrome or not
# change this value for a different output
my_str = 'aIbohPhoBiA'
# make it suitable for caseless comparison
my_str = my_str.casefold()
# reverse the string
rev_str = reversed(my_str)
# check if the string is equal to its reverse
if list(my_str) == list(rev_str): print("It is palindrome")
else: print("It is not palindrome")```

Output

`It is palindrome`

Note: To test the program, change the value of my_str in the program.

In this program, we have taken a string stored in my_str.

Using the method `casefold()` we make it suitable for caseless comparisons. Basically, this method returns a lowercased version of the string.

We reverse the string using the built-in function `reversed()`. Since this function returns a reversed object, we use the `list()` function to convert them into a list before comparing.

### Check out these related Python examples:

• Sort Words in Alphabetic Order
• Remove Punctuations From a String
• Count the Number of Each Vowel
• Check Armstrong Number
• Convert Decimal to Binary Using Recursion
• Check Prime Number
• Display Powers of 2 Using Anonymous Function
• Print the Fibonacci sequence

## Python Examples

 Add Two Matrices Transpose a Matrix Multiply Two Matrices Check Whether a String is Palindrome or Not Remove Punctuations From a String Sort Words in Alphabetic Order Illustrate Different Set Operations

close

### It looks like you are using Adblock!

It takes a lot of effort and cost to maintain Programiz. We would be grateful if you support us by either:

or

Donate on Paypal

• Statistical Functions in Python | Set 1 (Averages and Measure of Central Location)
• Statistical Functions in Python | Set 2 ( Measure of Spread)
• Bisect Algorithm Functions in Python
• Decimal Functions in Python | Set 1
• Decimal Functions in Python | Set 2 (logical_and(), normalize(), quantize(), rotate() … )
• NetworkX : Python software package for study of complex networks
• getpass() and getuser() in Python (Password without echo)
• Reading and Generating QR codes in Python using QRtools
• fnmatch – Unix filename pattern matching in Python
• Unicodedata – Unicode Database in Python
• Textwrap – Text wrapping and filling in Python
• Secrets | Python module to Generate secure random numbers
• pickle — Python object serialization
• Understanding Python Pickling with example
• copyreg — Register pickle support functions
• Python GUI – tkinter
• Python String
• Python Language Introduction
• Python List
• Find the first non-repeating character from a stream of characters
• Array in Python | Set 1 (Introduction and Functions)
• Python 3 basics
• Python Dictionary
• How to print without newline in Python?
• Python | Set 2 (Variables, Expressions, Conditions and Functions)
• Python String | split()
• Python map() function
• Object Oriented Programming in Python | Set 1 (Class, Object and Members)
• Heap queue (or heapq) in Python
• Reverse string in Python (5 different ways)

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

Given a string, write a python function to check if it is palindrome or not. A string is said to be palindrome if reverse of the string is same as string. For example, “radar” is palindrome, but “radix” is not palindrome.

Examples:

```Input : malayalam
Output : Yes
Input : geeks
Output : No```

## Recommended: Please try your approach on IDE first, before moving on to the solution.

1) Find reverse of string
2) Check if reverse and original are same or not.

filter_none

edit
close

play_arrow

brightness_4
code

 `# function which return reverse of a string ``def` `reverse(s): ``    ``return` `s[::``-``1``] `` ` `def` `isPalindrome(s): ``    ``# Calling reverse function ``    ``rev ``=` `reverse(s) `` ` `    ``# Checking if both string are equal or not ``    ``if` `(s ``=``=` `rev): ``        ``return` `True``    ``return` `False`` ` ` ` `# Driver code ``s ``=` `"malayalam"``ans ``=` `isPalindrome(s) `` ` `if` `ans ``=``=` `1``: ``    ``print``(``"Yes"``) ``else``: ``    ``print``(``"No"``) `

chevron_right

Output :

`Yes`

Iterative Method: This method is contributed by Shariq Raza. Run loop from starting to length/2 and check first character to last character of string and second to second last one and so on …. If any character mismatches, the string wouldn’t be palindrome.

Below is the implementation of above approach:

filter_none

edit
close

play_arrow

brightness_4
code

 `# function to check string is  ``# palindrome or not  ``def` `isPalindrome(``str``): `` ` `    ``# Run loop from 0 to len/2  ``    ``for` `i ``in` `xrange``(``0``, ``len``(``str``)``/``2``):  ``        ``if` `str``[i] !``=` `str``[``len``(``str``)``-``i``-``1``]: ``            ``return` `False``    ``return` `True`` ` `# main function ``s ``=` `"malayalam"``ans ``=` `isPalindrome(s) `` ` `if` `(ans): ``    ``print``(``"Yes"``) ``else``: ``    ``print``(``"No"``) `

chevron_right

Output:

`Yes`

Method using inbuilt function to reverse a string: This method is contributed by Shariq Raza. In this method, predefined function ‘ ‘.join(reversed(string)) is used to reverse string.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

brightness_4
code

 `# function to check string is  ``# palindrome or not ``def` `isPalindrome(s): ``     ` `    ``# Using predefined function to  ``    ``# reverse to string print(s) ``    ``rev ``=` `''.join(``reversed``(s)) `` ` `    ``# Checking if both string are  ``    ``# equal or not ``    ``if` `(s ``=``=` `rev): ``        ``return` `True``    ``return` `False`` ` `# main function ``s ``=` `"malayalam"``ans ``=` `isPalindrome(s) `` ` `if` `(ans): ``    ``print``(``"Yes"``) ``else``: ``    ``print``(``"No"``) `

chevron_right

Output:

`Yes`

This article is contributed by Sahil Rajput . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected] See your article appearing on the GeeksforGeeks main page and help other Geeks.

My Personal Notes
arrow_drop_up

## Recommended Posts:

• C Program to Check if a Given String is Palindrome
• Python program to check if string is empty or not
• Python program to check if a string contains all unique characters
• Python | Program to check if a string contains any special character
• Check if any anagram of a string is palindrome or not
• Check if a given string is a rotation of a palindrome
• Check if it is possible to create a palindrome string from given N
• Check if a string is palindrome in C using pointers
• Recursive function to check if a string is palindrome
• Check if there exists any sub-sequence in a string which is not palindrome
• Given two strings check which string makes a palindrome first
• Check if a string can be rearranged to form special palindrome
• Check if characters of a given string can be rearranged to form a palindrome
• Python | Check if binary representation is palindrome
• Check if the characters in a string form a Palindrome in O(1) extra space

Most popular in Python
• Linear Regression (Python Implementation)
• Keywords in Python | Set 1
• Global and Local Variables in Python
• How to split a string in C/C++, Python and Java?
• Important differences between Python 2.x and Python 3.x with examples

Most visited in School Programming
• Arrays in C/C++
• Print a given matrix in spiral form
• Basic Concepts of Object Oriented Programming using C++
• Writing first C++ program : Hello World example
• Program to find GCD or HCF of two numbers

Related Articles
• Remove duplicates from a given string
• Boggle | Set 2 (Using Trie)
• Minimum characters to be added at front to make string palindrome
• Python | Remove all duplicates words from a given sentence
• Find if a string is interleaved of two other strings | DP-33
• Minimum Number of Manipulations required to make two Strings Anagram Without Deletion of Character
• Write a program to print all permutations of a given string
• Longest Palindromic Substring | Set 1
• Prefix to Infix Conversion
• Ways to remove i’th character from string in Python
• Program to replace a word with asterisks in a sentence
• Print all permutations in sorted (lexicographic) order
• Python | Check for URL in a String
• Python | Permutation of a given string using inbuilt function
• Palindrome Partitioning | DP-17