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:

Tim Shaffer said...

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

Anonymous said...

print('!dlrow olleH'[::-1])

Anonymous said...

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

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

Anonymous said...

Perhaps

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

is simpler.
Cheers, D.

Vasudev Ram said...

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

Vasudev Ram said...

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

Thanks for pointing it out.

Vasudev Ram said...

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

Vasudev Ram said...

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

Vasudev Ram said...

@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).