Trusted answers to developer questions

How to check if a given string is a palindrome

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

A string is said to be a palindrome if it can be read the same from left to right as right to left.

Examples:- “Naman”, “Madam”,“Civic”.

First method

Usws the list to check if a given string is a palindrome:

def is_it_Palindrome(s):
return s == s[::-1]
# Driver code
s = "civic"
a = is_it_Palindrome(s)
if a:
print("Yes")
else:
print("No")

Second method

Uses the for loop(iterator) to check if a given string is a palindrome:

def is_it_Palindrome(str):
# Run loop from 0 to len//2
for i in range(0, len(str)//2):
if str[i] != str[len(str)-i-1]:
return False
return True
# main function
s = "civic"
a = is_it_Palindrome(s)
if (a):
print("Yes")
else:
print("No")

Third method

Uses the built-in reversed function to check if a given string is a palindrome.

def is_it_Palindrome(s):
# Using predefined function to
# reverse to string print(s)
rev = rev = ''.join(reversed(s))
# Checking if both string are
# equal or not
if (s == rev):
return True
return False
# main function
s = "civic"
a = is_it_Palindrome(s)
if (a):
print("Yes")
else:
print("No")

RELATED TAGS

python
Did you find this helpful?