Palindrome in Python

Growing up and learning computers, we all have found ourselves fascinated by strings of peculiar sequences or numbers. Reading reverse strings was fun when we were little, and as we grew from computer science lovers to coding enthusiasts, we learned that strings that read the same both ways are called palindromes in Python.

Consequently, we took our love for coding further by wanting our machines to understand what palindromes are and how to check them in Python using different ways. Python enthusiasts, let’s admit no other language can do it better.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

What is a Palindrome?

For a number or string to be palindrome in Python, the number or string must be the same when inverted. If the string or number does not remain unaltered when reversed, it is not a Palindrome.

For instance, 11, 414, 1221, and 123321 are palindrome numbers in Python.

MOM, MADAM, and RADAR are palindrome strings in Python.

Example: KAYAK

Output: Yes, a palindrome string.

Example: 1234321

Output: Yes, a palindrome number.

Therefore, a palindrome in Python is any word, number, sentence, or string that reads the same backward or forward. 

Methods to Check Palindrome in Python

A palindrome program in Python allows us to check whether the given string or number is a Palindrome.  Moreover, there are several methods in Python to determine this; as a beginner or learner in Python, we have encountered this several times.

Using the reverse and compare method

To use this procedure, which was previously mentioned, we will first look for the reversed string and then compare it to the original string. It is a palindrome if the strings line up. It is as easy as it seems!

#Define a function 

def isPalindrome(string): 

if (string == string[::-1]) : 

return "The string is a palindrome." 

else: 

return "The string is not a palindrome." 

#Enter input string 

string = input ("Enter string: ") 

print(isPalindrome(string))

Enter string: dad

The string is a palindrome.

The isPalindrome() method is first declared in the code above, and the string argument is passed in.  

Then, using the slice operator string[::-1], we get the input string's reverse. The step option, in this case, is -1, which guarantees that the slicing will begin at the end of the string and move back one step each time. 

It is now a palindrome if the reversed string equals the input string. 

Otherwise, it wouldn't be a palindrome.

Using inbuilt method

The predefined function "'.join(reversed(string))" is used in this method to reverse the string.

# 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 = "radar"

ans = isPalindrome(s)

 

if (ans):

    print("Yes")

else:

    print("No")

Enter string: radar

The string is palindrome.

In this, by converting the input number to a sequence and utilizing the reversed technique to determine the reverse of the sequence, we can use Python's built-in reversed(sequence) function to check for palindromes. The palindrome can then be verified by comparing these two sequences.

Using for loop

In this method, we'll cycle through each character in the provided string using a for loop, joining it with each element kept in an empty variable we define.

#Enter input string 

string = input("Enter string : ") 

 

#Declare an empty string variable   

revstr = "" 

 

#Iterate string with for loop 

for i in string: 

    revstr = i + revstr   

print("Reversed string : ", revstr) 

 

if(string == revstr): 

   print("The string is a palindrome.") 

else: 

   print("The string is not a palindrome.")

Enter string: malayalam

Reversed string: malayalam

The string is a palindrome.

Therefore,  a string is referred to as a palindrome if its reverse is the same string.

Using while loop

The most preferred choice among programmers because the string does not need to be reassigned throughout loop execution, a while loop is frequently used over a for loop because it allows the programme to use less memory for longer strings. 

#Define a function 

def isPalindrome(string): 

    string = string.lower().replace(' ', '') 

    first, last = 0, len(string) - 1 

    while(first < last): 

        if(string[first] == string[last]): 

            first += 1 

            last -= 1 

        else: 

            return "The string is not a palindrome." 

     

    return "The string is a palindrome." 

 

#Enter input string 

str1 = input("Enter string : ") 

 

print(isPalindrome(str1)) #Returns True

Enter string: kayak

The string is a palindrome.

Therefore, we begin by declaring the isPalindrome() method and supplying the string parameter in the code above.  

Next, two variables, first and last, are defined and given the values 0 and len(string) -1, respectively. We enter an input string in the code above. 

The input string is then iterated over all characters from beginning to end using the while loop. Whether the nth index value from the front and the nth index value from the back match will be determined by the loop. The function indicates that the string is a palindrome if True.  

Unlike a for loop, this loop ends immediately if the initial and last characters are not the same, and it does not check the full string. 

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Using the reverse and join method

In this instance, we'll cycle through the string's characters in reverse order using the built-in reversed() method. Next, in order to determine whether the input string is a palindrome, we will compare it with the inverted string. This is similar to the reverse and compare method.

#Define a function 

def isPalindrome(string): 

    revstr=''.join(reversed(string)) 

    if string==revstr: 

         return "The string is a palindrome." 

    return "The string is not a palindrome." 

 

#Enter input string 

string = input ("Enter string: ") 

 

print(isPalindrome(string))

Enter string: madam

The string is a palindrome.

The isPalindrome() method is first declared in the code above, and the string argument is passed in.  

The input string is then passed to the function body, where the reversed() function is used to loop through the string's characters backwards.  

The join() function is then used to unite the reversed characters, which are subsequently saved in the revstr variable.  

Next, we check to see if the reversed string—a palindrome—matches the input string using the if loop. It is not a palindrome. 

Using an iterative loop

In this method, we will run a loop from beginning to length/2, checking the string's initial character from the last one, its second from the second last, and so on. A character mismatch would prevent the string from being a palindrome.

#Define a function 

def isPalindrome(string): 

for i in range(int(len(string)/2)): 

if string[i] != string[len(string)-i-1]: 

return "The string is not a palindrome." 

return "The string is a palindrome." 

 

#Enter input string 

string = input ("Enter string: ") 

 

print(isPalindrome(string))

Enter string: tenet

The string is a palindrome.

The isPalindrome() function has been declared and the string argument has been supplied to it in the code above.  

Next, we execute a for loop from range 0 to the center of the input string in the function body. 

We verify if the nth index value from the front and the nth index value from the back match while the for loop executes.  

Consequently, the string is NOT a palindrome if they DO NOT match. 

If not, the string is a reversed pair. 

Using recursion

This technique uses the recursion approach, which is a process in which the function calls itself to reverse a string. Then, as in the earlier cases, we verify if the reversed string corresponds to the original string. 

#Define a function 

def isPalindrome(string): 

if len(string) < 1: 

return True 

else: 

if string[0] == string[-1]: 

    return isPalindrome(string[1:-1]) 

else: 

 return False 

 

#Enter input string 

str1 = input("Enter string : ") 

 

if(isPalindrome(str1)==True): 

   print("The string is a palindrome.") 

else: 

   print("The string is not a palindrome.")

Enter string: civic

The string is a palindrome.

The isPalindrome() method has once more been declared and given a string argument in the code above.  

Alternatively, the function is invoked recursively with the parameter as the sliced string with the first and last characters removed, returning False otherwise, if the string's end character matches its beginning character. 

Finally, we check whether the returned answer is True or False using an if statement, and then we print the output as indicated. 

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Conclusion

Hope this text tutorial was able to give you a complete understanding about how to implement Palindrome in Python. If you are looking to enhance your software development skills further, we would highly recommend you to check Simplilearn’s Professional Certificate Program in Full Stack Web Development - MERN. This course, in collaboration with IIT Madras, can help you hone the right development skills and make you job-ready in no time.

If you have any questions or queries, please feel free to post them in the comments section below. Our team will get back to you at the earliest.

FAQs

1. How to do a palindrome function in Python?

There are numerous ways to perform palindromes in Python. We can do this using reverse and compare method, in-built method, for loop, while loop, reverse and join, iterative loop and recursion method. 

2. How do you find a palindrome number?

Any number that runs back on itself or remains the same when reversed is a palindrome number. For example, 16461, 11 and 12321.

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.