How to make a palindrome in Python

Create a palindrome in Python with a simple example: reverse a string with slicing & reversed() for a mirrored result.

Making a Palindrome in Python

A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward, such as madam or racecar. This can be achieved in Python using a few simple steps.

First, we need to create a function that will take a string as an argument and determine if it is a palindrome or not. To do this, we can use the reverse function from the string library. This function takes a string as an argument and returns a new string that is the reverse of the original string.

def is_palindrome(string):
    if string == string[::-1]:
        return True
    else:
        return False

Next, we need to create a loop that will iterate through each character of the string and check if it is a palindrome. We can use a for loop to do this. The loop should start at the beginning of the string, check if the character is a palindrome, then move on to the next character.

for i in range(len(string)):
    if is_palindrome(string[i:]):
        print(string[i:])

Finally, we can print out the palindrome. If the string is a palindrome, the output will be the same as the input. Otherwise, it will be the longest palindrome contained within the original string.

if is_palindrome(string):
    print(string)
else:
    print(string[0:i+1])

Let's try running this code on the string "abccba".

string = "abccba"

def is_palindrome(string):
    if string == string[::-1]:
        return True
    else:
        return False

for i in range(len(string)):
    if is_palindrome(string[i:]):
        print(string[i:])

if is_palindrome(string):
    print(string)
else:
    print(string[0:i+1])

The output of this code is "abccba", which is the palindrome contained within the original string. We have successfully created a palindrome in Python!

Answers (0)