Reverse a string

October 9th, 2006 toydi Posted in python, rev | Hits: 54385 | 10 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

10 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.

Leave a Reply