x.reverse() list function JES

Posted 10 July 2012 - 03:49 PM

I am very new to all of this. I am learning Python through JES. I am trying to write a program to determine if a word is a palindrome--you know like BOB forwards and backwards. I do not want it done for me! My approach is to essentially pull the string and reverse it. Then if the two are equal.... However, my materials cover very little about using reverse(). It appears only a few times in the command area, not written into any programs. Is it possible to incorporate reverse() into my program? If so how?

Replies To: x.reverse() list function JES

Re: x.reverse() list function JES

Posted 10 July 2012 - 04:04 PM

You have the right idea, but there's a couple of complications you need to take care of:

The reverse method only works on lists, not strings, so you need to convert your string to a list of characters before you can use reverse. You can do that using list(the_string). You can then call .reverse() on that list to reverse it - note that this works in-place, so you don't use reverse's return value, but instead the original list is modified.

Also note that comparing a string against a list will always give you False, so you need to convert the original string to a list again and compare that against the reversed list.

An alternative approach is to use the reversed function instead of the reverse method. Unliked reversereversed works with any kind of sequence - not just lists. So you don't need to convert your string to a list to use it. But you do need to convert the result back to a string because reversed returns a generator, not a string. To convert the reversed generator back to a string, you can use the join method.