Python: Check If a String is a Palindrome
 |
| Palindrome |
The Challenge
- improving the student's skills in operating with strings;
- encouraging the student to look for non-obvious solutions.
Scenario
Do you know what a palindrome is?
It's a word which look the same when read forward and backward. For example, "kayak" is a palindrome, while "loyal" is not.
Your task is to write a program which:
- asks the user for some text;
- checks whether the entered text is a palindrome, and prints result.
Note:- assume that an empty string isn't a palindrome;
- treat upper- and lower-case letters as equal;
- spaces are not taken into account during the check - treat them as non-existent;
- there are more than a few correct solutions - try to find more than one.
Test your code using the data we've provided.
Test data
Sample input:
Ten animals I slam in a net
Sample output:
It's a palindrome
Sample input:
Eleven animals I slam in a net
Sample output:
It's not a palindrome
Solution Code:
""" method 1 - detailed variables"""
text = input("Enter a text\n")
a_string = text.lower().replace(' ', '')
b_string = a_string[::-1]
while not text:
print("It's not a palindrome")
break
else:
if a_string == b_string:
print("It's a palindrome")
else:
print("It's not a palindrome")
""" method 2 - reversed() function"""
text = input("Enter a text\n")
text = text.lower().replace(" ", "")
rev_text = "".join(reversed(text))
while not text:
print("It's not a palindrome")
break
else:
if text.casefold() == rev_text.casefold():
print("It's a palindrome")
else:
print("It's not a palindrome")
""" methos 3 - for loop """
text = input("Enter a text\n")
def palindrome(string):
if text == "":
print("It's Not a palindrome")
string = string.lower().replace(' ', '')
reversed = ''
for i in range(len(string[::-1])):
reversed += string[::-1]
if string == reversed:
return "It's a palindrome"
else:
return "It's Not a palindrome"
print(palindrome(text))
methos 4 - while loop"""
text = input("Enter a text\n")
def palindrome(string):
while len(string.strip()) ==0:
return "It's Not a palindrome"
string = string.lower().replace(' ', '')
first, last = 0, len(string) - 1
while(first < last):
if(string[first] == string[last]):
first += 1
last -= 1
else:
return "It's Not a palindrome"
return "It's a palindrome"
print(palindrome(text))
Still, there are other solutions, and other ways to make the mentioned solutions better. Can you think about them?
See you in the comments 👀
Remember "Learn Less, Practice More"
Understanding Palindrome Logic
A palindrome is a word, phrase, or sequence that reads the same forward and backward, such as "radar", "level", or "noon". Checking whether a string is a palindrome is a classic programming exercise because it brings together a few core Python ideas: comparing characters, reversing a string, and normalizing input.
One common approach is to compare the string with its reverse, for example using slicing with [::-1], so that the program is true when the original equals its reversed form. Another approach is to compare the first character against the last, then move inward toward the center, which is efficient because it stops as soon as a mismatch is found. Careful handling of the loop logic is required so that the check works correctly for strings of both even and odd length, and this is exactly the kind of condition that the Lab asks you to reason through.
Key Takeaways
- A palindrome reads the same forward and backward.
- Palindrome checks reinforce string indexing, slicing, and comparison logic in Python.
- The reverse-and-compare method and the two-pointer method are the two most common solutions.
- Edge cases such as single-character strings and even-length strings are important to handle correctly.
Frequently Asked Questions
What is the easiest way to check for a palindrome in Python?
Comparing the string to its reverse via slicing, s == s[::-1], is the simplest approach and reads clearly. Many instructors also expect you to solve it with a loop to demonstrate index handling.
Should I ignore spaces, punctuation, and letter case?
It depends on the specification. In this Lab, the test data defines the expected behavior, so follow the scenario precisely. In general, phrases with spaces and punctuation may need the input cleaned before comparison.
Why does the Lab ask for a manual loop instead of the reverse slice?
Writing the loop checks your understanding of indexing and conditionals rather than relying on a built-in shortcut. It is a conceptual exercise, so the loop-based solution is the point of the task.
Comments
Post a Comment
Your opinion matters, your voice makes us proud and happy. Your words are our motivation.