Reverse a string

October 9th, 2006 toydi Posted in python, rev | Hits: 68219 | 12 Comments »

python provides a -c option to accept and run a script line.

To reverse a string like this one: “toydi deified idiot”.

echo 'toydi deified idiot' | python -c "print raw_input()[::-1]" 
  1. echo prints the string to stdout.
  2. python run the script line.
  3. raw_input() read from stdin (to read from pipe and return the string).
  4. [::-1] simply says: steps through and return each character in the string, but in reverse order (-1).
  5. print prints the reversed string to stdout:
toidi deified idyot

Have fun with python!
Wait.. ok, actually, rev will just do the job:

echo  "toidi deified idyot" | rev

12 Responses to “Reverse a string”

  1. I thought this was Linux by Examples, not Python :P.

    So I’m going to add some ruby mix to the fun.

    echo "ruby r  roxors" | ruby -e '$stdin.each { |line| puts line.reverse }'

    You’ll get an extra line at the top because it also reversed the new line character.

  2. echo -ne “string” does not generate newline

  3. Rajesh Duggal Says:

    echo “ruby r roxors” | ruby -lne ‘puts $_.reverse’

  4. i need bash command for reversing a string.

  5. Native BASH command is rev.

  6. yopeeeeee!!!!!!!!!11
    tnx a lot

  7. Thanks a lot. Great help

  8. […] J’ai trouvé ça ici : REVERSE A STRING. […]

  9. whitch predefine function using in linux string riverse program.

  10. Good day! This is my first visit to your blog! We are a group of volunteers and starting a new
    initiative in a community in the same niche. Your blog provided
    us valuable information to work on. You have done a outstanding job!

    my page: Klondike Cheats

  11. What’s up everyone, it’s my first pay a visit at this site, and post is genuinely fruitful in support
    of me, keep up posting such content.

Leave a Reply