To check if a given string is a palindrome in Python, you need to verify if the string reads the same forwards and backwards. Here’s how you can write a Python program to check for palindromes:
- Using slicing to reverse the string:
def is_palindrome(s): # Remove spaces and convert to lowercase
s = s.replace(" ", "").lower()
# Check if the string is equal to its reverse
return s == s[::-1]
- Using a loop to compare characters from start to end:
def is_palindrome(s): # Remove spaces and convert to lowercase
s = s.replace(" ", "").lower()
# Initialize pointers for the start and end of the string
start = 0
end = len(s) - 1
# Check characters from start and end towards the center
while start < end:
if s[start] != s[end]:
return False
start += 1
end -= 1
return True
Example Usage:
You can test the is_palindrome function with different strings:
string1 = "A man a plan a canal Panama"string2 = "racecar"
string3 = "hello"
print(f"Is '{string1}' a palindrome? {is_palindrome(string1)}") # Output: True
print(f"Is '{string2}' a palindrome? {is_palindrome(string2)}") # Output: True
print(f"Is '{string3}' a palindrome? {is_palindrome(string3)}") # Output: False
Explanation:
Both implementations (
is_palindromefunctions) start by removing spaces and converting the string to lowercase to handle case insensitivity and ignore spaces in the palindrome check.Using slicing (
s == s[::-1]): This approach creates a reversed version ofsand directly compares it tos.Using a loop (
while start < end): This method iterates through the string from both ends towards the center (startfrom the beginning andendfrom the end), comparing characters. If any pair of characters doesn't match, it returnsFalse; otherwise, it returnsTrueif the entire string is checked without finding any mismatches.
Both methods are efficient and straightforward for checking if a string is a palindrome in Python. The choice between them can depend on personal preference or specific requirements of your application.

