Reversing a string in python – version the first


python -c 's = "The rain in spain falls mainly on the plain."; print "".join(s[c] for c in xrange(len(s) - 1, -1, -1))'

Advertisements

6 thoughts on “Reversing a string in python – version the first

  1. You might want to try using the slice syntax for reversing strings.


    s = "The rain in spain falls mainly on the plain."
    print s[::-1]

    The slice syntax in Python is a lot like the range() function. It supports a start, stop and step value [start:stop:step]. Leaving out the start and stop values causes Python to use the defaults which is 0 for the start value and the last index in the string for the stop value. Specifying -1 tells Python to count down from the stop to the start, 1 item at a time.

    From the command line it would look like this:

    python -c ‘print “The rain in spain falls mainly on the plain.”[::-1]’

    • Nice. I’m using that one in a post for tomorrow. I got the same feedback from a cousin of mine. And I had a middle of the night inspiration that got me slightly closer to the final solution before he showed me the same solution.

  2. reversed() also returns an iterator and is a bit more Pythonic, even compared to [::-1].

    s = “The rain in spain falls mainly on the plain.”
    print “”.join(reversed(s))

    PEP 322 describes reversed() in a little more detail.

    And from the command line:

    python -c ‘print “”.join(reversed(“The rain in spain falls mainly on the plain.”))’

  3. Pingback: Reversing a String in Python « Pointless Programming

  4. Pingback: Reversing a String in Python « Blog 4

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s