Search code examples
pythonarrayspython-3.xstringpalindrome

Checking a string if it is a valid palindrome or not using python3


class Solution:
    def isPalindrome(self, s: str) -> bool:
        string=''
        ss=s.lower()
        
        for x in ss:
            if x.isalnum():
                string.join(x)
        bol= string == string[::-1]
                
        return bol
str_1="A man, a plan, a canal: Panama"  
str_2="race a car"  

For str_1 the code is working properly (output is TRUE) but for str_2 also the output is TRUE but it is not a palindrome. I couldn't understand whats the error in my code.


Solution

  • Because you are not saving every time that you are joining the string.

    class Solution:
        def isPalindrome(self, s: str) -> bool:
            string=''
            ss=s.lower()
            
            for x in ss:
                if x.isalnum():
                    string += ''.join(x) # Remember to save the new added character
            bol= string == string[::-1]
                    
            return bol