1 Replies - 1754 Views - Last Post: 10 July 2012 - 04:04 PM Rate Topic: -----

#1 manticmadman  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 10-July 12

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?

Is This A Good Question/Topic? 0
  • +

Replies To: x.reverse() list function JES

#2 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2307
  • View blog
  • Posts: 3,569
  • Joined: 21-June 11

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 reverse reversed 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.

This post has been edited by sepp2k: 10 July 2012 - 04:06 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1