Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Palindrome
#1
def isStringPalindrome(string):
  
  rString=''
  def reverse(string):
    index=len(string)
    while index>0:
      rString=rString+string[index-1]
      index=index-1


  if string==rString:
    print('String is Palindrome')
  else:
    print('string is not palindrome')
    

isStringPalindrome('reviver')
Why is this not working as it is printing back string is not palindrome when it is?
Reply
#2
Try he below code.
You were not calling the reverse function anywhere and it had no return statement.

def isStringPalindrome(string):
   
  
    def reverse(string):
      
        rString=''
        index=len(string)
        while index>0:
            rString=rString+string[index-1]
            index=index-1      
      
        return rString
 
 
    if string==reverse(string):
        print('String is Palindrome')
    else:
        print('string is not palindrome')


print(isStringPalindrome('abba'))
Reply
#3
that works!
thank you
Reply
#4
You could also use slicing:

a_string = "Anna".lower()
rev_string = a_string[::-1]

if rev_string == a_string:
    print("True")
else:
    print("False")
Notice we change 'a_string' to lowercase, otherwise 'Anna' would reverse as 'annA', resulting in a "False'
If it ain't broke, I just haven't gotten to it yet.
OS: Windows 10, openSuse 42.3, freeBSD 11, Raspian "Stretch"
Python 3.6.5, IDE: PyCharm 2018 Community Edition
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Simple Palindrome Inkanus 4 2,102 Nov-25-2020, 04:11 PM
Last Post: perfringo
  Palindrome in Python - result always false RavCOder 13 6,703 Oct-16-2019, 01:38 PM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020