ROT13 in Python

2007-01-31 01:17:14 UTC

Patr1ck has posted instructions on performing ROT13 in Ruby. Colin has responded with the Perl version. Here’s the Python version.

import codecs
rot13ed_data = codecs.getencoder(‘rot13’)(data_to_rot13)[0]

That is all.

5 Responses to “ROT13 in Python”

  1. Dan H Says:

    If you want a command line script, is there a better way to handle the input argument than this?

    #! /usr/bin/python
    # Usage:
    # rot13.py ‘Hello, my name is Bob!’
    import sys
    import codecs
    data_to_rot13 = str(sys.argv[1:])
    rot13ed_data = codecs.getencoder(‘rot13’)(data_to_rot13)[0]
    print rot13ed_data

    Also, this live preview thing is neat. Is that a plugin?

  2. Jamie Says:

    Python rocks my friend…thanks for convincing me. Used SWIG for the first time in the last few days…check it out.

  3. Peter Hosey Says:

    [quote=”Dan H”]If you want a command line script, is there a better way to handle the input argument than this?

    data_to_rot13 = str(sys.argv[1:])[/quote]

    First, str(some_list) applied to a list will get you the repr of it:

    >>> str([‘a’, ‘b’])
    “[‘a’, ‘b’]”

    The correct way is ‘ ‘.join.

    Even so, I generally use optparse for such things, even if I’m not going to have options, unless it’s a one-off script that I don’t care about.

    import optparse
    parser = optparse.OptionParser(usage=’%p “Hello, my name is Bob!”‘)
    opts, args = parser.parse_args()
    data_to_rot13 = ‘ ‘.join(args)

    The advantage of this is that I can easily add options later.

    [quote]Also, this live preview thing is neat. Is that a plugin?[/quote]

    Aye. It’s called Live Comment Preview.

  4. Andrew Says:

    It’s even shorter in vim: g?G

  5. Matt Says:

    #!/bin/sh
    echo $1 | tr A-Za-z N-ZA-Mn-za-m

Leave a Reply

Do not delete the second sentence.