Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
community creator

How to check if a given string is a palindrome

Srujan

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
community creator
RELATED COURSES

View all Courses

Keep Exploring