How to Check if String is a Palindrome in Python

0 min read 81 words

The challenge

Write a function that checks if a given string (case insensitive) is a palindrome.

The solution in Python

Option 1:

def is_palindrome(s):
    s = s.lower()
    for i, item in enumerate(s):
        if i<len(s)/2:
            if s[i]!=s[len(s)-i-1]:
                return False
    return True

Option 2:

def is_palindrome(s):
    s = s.lower()
    return s == s[::-1]

Option 3:

def is_palindrome(s):
    return s.lower()==s[::-1].lower()

Test cases to validate our solution

@test.describe('sample tests')
def sample_tests():
    test.assert_equals(is_palindrome('a'), True)
    test.assert_equals(is_palindrome('aba'), True)
    test.assert_equals(is_palindrome('Abba'), True)
    test.assert_equals(is_palindrome('malam'), True)
    test.assert_equals(is_palindrome('walter'), False)
    test.assert_equals(is_palindrome('kodok'), True)
    test.assert_equals(is_palindrome('Kasue'), False)
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts