Thursday, July 25, 2024

Nitheen Kumar

Write a Program to check if a given string is a palindrome in Python

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:

  1. 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]
  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

Write a Program to check if a given string is a palindrome in Python

Explanation:

  • Both implementations (is_palindrome functions) 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 of s and directly compares it to s.

  • Using a loop (while start < end): This method iterates through the string from both ends towards the center (start from the beginning and end from the end), comparing characters. If any pair of characters doesn't match, it returns False; otherwise, it returns True if 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.


Subscribe to get more Posts :