OBJECTIVE: Check to see if a given string is a palindrome (aka. is the same backwards as it is forwards).
Intuitively, the easiest way to go about this is to use the previous code (the string reverser) and to check if both strings are the same. The difference here is that you need to save the reversed string into a variable, as such:
word = raw_input('Enter a string to see if it is a palindrome: ');
word_backwards = ''.join([word[i] for i in xrange(len(word)-1, -1, -1)]);
Then simply check to see if word == word_backward.
But remember that the function "==" checks to see if the strings are EXACTLY alike, which means that capitalization is taken into consideration. We obviously don't want this, so the easiest way is to convert them both into either or.
In my example here, I decided to convert them into lowercase during the if statement. The syntax for converting a string into lowercase is:
string.lower()
Hence:
if (word.lower() == word_backwards.lower()):
print ("YES, " + word + " is a palindrome.");
else:
print ("NO, " + word + " is NOT a palindrome.");
To tighten this code up (as I have not done on the previous post), I'd want to make this program loop until the user types in exit. That way, I don't have to run the code separately every time. I do this using a WHILE loop, such that a variable for instance power == True, I continue to run the program. Using three instances of IF loops, I am able to complete this code, with the three instances being:
- If word typed in was "exit", then close the program
- Else if word = word backwards, then return True.
- Else, return False.
TL;DR:
power = True;
while power == True:
word = raw_input('Enter a string to see if it is a palindrome (type exit to quit program): ');
word_backwards = ''.join([word[i] for i in xrange(len(word)-1, -1, -1)]);
if (word == "exit"):
power = False;
print ("Palindrome Checker has been closed.");
elif (word.lower() == word_backwards.lower()):
print ("YES, " + word + " is a palindrome.");
else:
print ("NO, " + word + " is NOT a palindrome.");
Example of Palindrome Checker using Notepad++ |