Python Program to Check Whether a String is Palindrome or Not

Posted in

Python Program to Check Whether a String is Palindrome or Not

    Here in this article, we have provided two python source codes which can tell whether the user entered string is a palindrome or not.

    Prerequisite topics to create this program

    • Python if....else statement
    • Python string
    • Python string methods
    • Python comparison operator.
    • Python For loop

    Palindrome String

    If a string makes the same sense whether you read it forward or backward then it would be a palindrome string.

    Steps(Using String methods)

    • Ask the user to enter the string.
    • Lower case the string.
    • Reverse the string using the string slicing method and store it in a temporary variable.
    • Now use the if...else and comparisons operator to check if the entered string and its reverse are the same.

    Python Program to Check Whether a String is a Palindrome or Not (Using string methods)

    Code:

    string = input("Enter the String: ").lower()
    temp = string[::-1]
    if string == temp:
        print(string ," is a palindrome string ")
    else:
        print(string, " is not a palindrome")

    Output 1:

    Enter the String: dad
    dad is a palindrome string

    Output 2:

    Enter the String: hello
    hello is not a palindrome

    Steps(Using for loop)

    • Ask the user to enter the string.
    • Lower case the string.
    • Create a variable b which holds the length of the string.
    • create a loop from range 0 to the length of the string itself.
    • Inside the loop create a logic in which we keep comparing the string forward character with the backward characters.

    Python Program to Check Whether a String is a Palindrome or Not (Using For loop)

    Code

    string = input("Enter the String: ").lower()
    b= len(string)-1
    for f in range(len(string)):
        if string[f]==string[b]:
            b-=1
        else:
            print(string, " is not a palindrome")
            break
               
    if f == len(string)-1:
        print(string ," is a palindrome string ")

    Output 1

    Enter the String: dad
    dad is a palindrome string

    Output 2

    Enter the String: hello
    hello is not a palindrome

    People are also reading:

    Vinay
    Written by

    Vinay Khatri

    I am a Full Stack Developer with a Bachelor's Degree in Computer Science, who also loves to write technical articles that can help fellow developers.