Reversing a string

Will Maier willmaier at ml1.net
Wed Jun 27 13:07:55 EDT 2007


On Wed, Jun 27, 2007 at 12:53:36PM -0400, Scott wrote:
> So how on earth would be the best way to: Write a function that
> takes a string as an argument and outputs the letters backward,
> one per line.

    >>> def rev(forward):
    ...     backward = list(forward)
    ...     backward.reverse()
    ...     return ''.join(backward)
    >>> rev("spam")
    'maps'

list.reverse() changes the list in-place. Instead of iterating over
the items in the string sequence, you can just convert the input
string outright.

-- 

[Will Maier]-----------------[willmaier at ml1.net|http://www.lfod.us/]



More information about the Python-list mailing list