Kawin M
Kawin M

Reputation: 306

How to check if a string is a palindrome?

I have a code to check whether a word is palindrome or not:

str = input("Enter the string")
l = len(str)
p = l-1
index = 0
while index < p:
    if str[index] == str[p]:
        index = index + 1
        p = p-1
        print("String is a palindrome")
        break
    else:
        print("string is not a palindrome")

If a word is inputted, for example : rotor , I want the program to check whether this word is palindrome and give output as "The given word is a palindrome".

But I'm facing problem that, the program checks first r and r and prints "The given word is a palindrome" and then checks o and o and prints "The given word is a palindrome". It prints the result as many times as it is checking the word.

I want the result to be delivered only once. How to change the code?

Upvotes: 6

Views: 22199

Answers (9)

M.Hassan Nasir
M.Hassan Nasir

Reputation: 851

You can also do it by using ternary operators in python.

string = "Madam"
print("palindrome") if string == string[::-1] else print("not a palindrome")

Upvotes: 0

RAHUL KUMAR
RAHUL KUMAR

Reputation: 1173

string = 'ASDBDSA'
if string[:]==string[::-1]:
     print("palindrome")
else:
     print("not palindrome")

Upvotes: 0

maria
maria

Reputation: 1

def palindrome(s):
    if len(s)<1:
       return True
    else:
        if s[0]==s[-1]:
           return palindrome(s[1:-1])
        else:
           return False
a=str(input("enter data")
if palindrome(a) is True:
    print("string is palindrome")
else:
    print("string is not palindrome")

Upvotes: 0

user11698085
user11698085

Reputation:

the easiest way is

str = input('Enter the string: ')

if str == str[::-1]:
   print('Palindrome')
else
   print('Not')

the same login can also be applied to number palindrome

Upvotes: 0

Deepak Tiwari
Deepak Tiwari

Reputation: 1

Change your implementation to the following one:

string_to_be_checked = input("enter your string ")
if string_to_be_checked == string_to_be_checked[::-1] :
    print("palindrome")
else:
    print("not palindrome")

Upvotes: 0

zorze
zorze

Reputation: 198

I see that most of the solutions in the internet is where either the string is taken as an input or the string is just reversed and then tested. Below is a solution that considers two points: 1) The input is a very large string therefore, it cannot be just taken from a user. 2) The input string will have capital casing and special characters. 3) I have not looked into the complexity and see further improvement. Would invite suggestions.

    def isPalimdromeStr(self, strInput):
        strLen = len(strInput)
        endCounter = strLen - 1
        startCounter = 0
        while True:
#             print(startCounter, endCounter)
#             print(strInput[startCounter].lower(), strInput[endCounter].lower())

            while not blnValidCh(self, strInput[startCounter].lower()):
                startCounter = startCounter + 1

            while not blnValidCh(self, strInput[endCounter].lower()): 
                endCounter = endCounter - 1

#             print(startCounter, endCounter)
#             print(strInput[startCounter].lower() , strInput[endCounter].lower())
            if (strInput[startCounter].lower() != strInput[endCounter].lower()):
                return False
            else:
                startCounter = startCounter + 1
                endCounter = endCounter - 1

            if (startCounter == strLen - 1):
                return True

#             print("---")


    def blnValidCh(self, ch):
        if rePattern.match(ch):
            return True

        return False

global rePattern
rePattern = re.compile('[a-z]')

blnValidPalindrome = classInstance.isPalimdromeStr("Ma##!laYal!! #am")
print("***")
print(blnValidPalindrome)  

Upvotes: 1

KingKong BigBong
KingKong BigBong

Reputation: 313

[::-1]

This code is the easiest way of reversing a string. A palindrome is something that reads the same regardless of what side you're reading it from. So the easiest function to check whether or not the word/string is recursive or not would be:

def checkPalindrome(s):
    r = s[::-1]
    if s == r:
        return True
    else:
        return False

Now you can check this code. Eg:

checkPalindrome("madam")
>>> True
checkPalindrome("sentence")
>>> False

Upvotes: 0

Antimony
Antimony

Reputation: 2240

I had to make a few changes in your code to replicate the output you said you saw.

Ultimately, what you want is that the message be displayed only at the end of all the comparisons. In your case, you had it inside the loop, so each time the loop ran and it hit the if condition, the status message was printed. Instead, I have changed it so that it only prints when the two pointers index and p are at the middle of the word.

str = input("Enter the string: ")
l = len(str)
p = l-1
index = 0
while index < p:
    if str[index] == str[p]:
        index = index + 1
        p = p-1
        if index == p or index + 1 == p:
            print("String is a palindrome")
    else:
        print("string is not a palindrome")
        break

Upvotes: 2

AlanK
AlanK

Reputation: 9833

Just reverse the string and compare it against the original

string_to_check = input("Enter a string")

if string_to_check == string_to_check[::-1]:
    print("This is a palindrome")
else:
    print("This is not a palindrome")

Upvotes: 8

Related Questions