Re: Reversing a string

vbr at email.cz vbr at email.cz
Wed Jun 27 13:26:07 EDT 2007


> ------------ Původní zpráva ------------
> Od: Will Maier <willmaier at ml1.net>
> Předmět: Re: Reversing a string
> Datum: 27.6.2007 19:08:40
> ----------------------------------------
> 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/]
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 
> 
> 

Or using string slice with negative step?

>>> "spam"[::-1]
'maps'

or one letter per line:

>>> print "\n".join("spam"[::-1])
m
a
p
s


Greetings,

Vlastimil Brom



More information about the Python-list mailing list