2005-11-28

Python One-liners

I love to hate Python. Conversely, I hate to love Python. One of its nice aspects is its fairly rigid syntax. When the language is limited, you speak it in simple, uninspired sentences. "I eat food." "Where is dog?" "For i in range(10): print i" And so on.

Perl, on the other hand, is like Chaucer sometimes. The lyf so short, the syntax so long to learn. You can do some heady shit with Perl, and a statement like

  $out{"$File::Find::dir"}++;

is perfectly fine. Perl gurus will notice the $var{"$another_var"} layout of this and immediately note that var, and therefore out, must be a hash. This takes a little bit of familiarity with the language, so much so that I, author of the above line, have had to reparse it mentally in order to recognize that fact in the past.

With Python, syntax is a lot more clean-looking, and Python code generally lacks Perl's trademark "I fired a shotgun filled with punctuation at it" style. Yet there is one thing that Perl does better, and that is to provide haggard sysadmins like myself with a fast way to do quite literally anything the interpreter is capable of doing: the one-liner. In Perl, this is the "-e" flag, as in

  $ perl -e 'print "Hello world!\n";'

Perl can do some pretty neat stuff. You can do RSA encryption in three lines, for instance, but even that's a little much for the guy who just wants a few strings converted into lowercase.

Python, I have been told, can do this as well, but the limitations of the language have proved slightly daunting. When "import string" has always gone on one line, by itself, how do you put the rest of your Python mojo on the same line?

I'll skip the rest of the boring and get straight to the solution: it's the semicolon.

  $ python -c 'import string; print string.lower("HELLO WORLD!")'

Handy.

Update 1: For comparison, the way to lowercasify a string in one line of Perl is as follows:

  $ perl -e 'print lc("HELLO WORLD!\n");'

Update 2: Like Perl, there is usually another way to do something in Python. In this case, you can skip the explicit import entirely by using the lower() method of the string you have provided:

  $ python -c 'print "HELLO WORLD!".lower()'

No comments: