Pages

Wednesday, November 26, 2014

A first Python one-liner

By Vasudev Ram

1. Install Python 2.7 (if you don't have it already).

2. Run this at the command line:

python -c "print ''.join(list(reversed('!dlrow olleH')))"

- Vasudev Ram - Dancing Bison Enterprises

Contact Page

9 comments:

  1. Why don't you encourage new users to use Python 3?

    ReplyDelete
  2. $ python -c "print ''.join(list(reversed('!dlrow olleH')))"
    -bash: !dlrow: event not found

    Perfect way to introduce someone to the joys of escaping characters.

    ReplyDelete
  3. Perhaps

    python -c "print('dlrow olleH'[::-1])"

    is simpler.
    Cheers, D.

    ReplyDelete
  4. @Tim Shaffer: That's a good question.
    Partly it has been because of the issue of not all libraries having been ported to Python 3 yet, and that there has been a lot of controversy on forums about 2 vs 3, but that has been going on for a while now, and I do know that progress is being made on the porting front. Also, unless more people make the effort (both to use 3 and port stuff to it, things will stay the same). So I think you make a good point, and I'll try to write more about 3 in future, some of the time; I'm not dropping 2 entirely, at least for a while.

    ReplyDelete
  5. @anonymous #!: Yeah, I forgot about sequence slicing and that idiom until after I hit Publish.

    Thanks for pointing it out.

    ReplyDelete
  6. I meant Anonymous #1, not #! - call it a Unixian slip :-)

    ReplyDelete
  7. @Anonymous #2:

    >Perfect way to introduce someone to the joys of escaping characters.

    Thanks for pointing this out. But:

    I tested it on Windows, because I was working on that at the time of writing the post. It works fine on Windows. I know about quoting issues on Unix, just didn't run it there. Also see below.

    Did you see the labels on the post? "humor"? ... It was not really meant as a tutorial for beginners, just as a quirky hello world one-liner.

    Also, caveat lector.

    People should not blindly accept any code they see on the Net. Not that I meant the mistake intentionally, of course.

    Cheers ...

    ReplyDelete
  8. @Anonymous #1:

    >I forgot about sequence slicing and that idiom

    I mean, I obviously know slicing, but forgot that negative-stride-of-1 thing:

    For those who don't know about slice strides in Python:

    https://www.google.co.in/search?q=python%20slice%20stride

    Also try these at the Python interpreter prompt:

    >>> s = "abcdefghij"
    >>> s[-1:0:-3]
    'jgd'
    >>> s[-1::-3]
    'jgda'
    >>>
    Note the difference in the output between specifiying a 0 vs. not, for the end of the range (the middle number in the square brackets).

    ReplyDelete

Please be on-topic and civil in your comments. Comments not following these guidelines will be deleted.