[Tutor] Simple ROT-13 Script

Karl Pflästerer sigurd at 12move.de
Tue Feb 3 12:59:32 EST 2004


On  3 Feb 2004, Javier JJ <- python.tutorial at jarava.org wrote:

> And the reason that it wont' work on other than ASCII.- strings ??

[...]
> Traceback (most recent call last):
>   File "<interactive input>", line 1, in ?
>   File "C:\Python23\lib\encodings\rot_13.py", line 18, in encode
>     return codecs.charmap_encode(input,errors,encoding_map)
> UnicodeDecodeError: 'ascii' codec can't decode byte 0xf1 in position
> 3: ordinal not in range(128)
>  >>>
                  ^^^^^^^^^^^ 
The reason is here           ; the error code says that that function
only works for characters in the ASCII range.

If you see how you do rot13 with pen and paer it's clear why it's so:


>>> alph = ''.join(map(chr, range(ord('a'), ord('z')+1)))
>>> alphrot = alph[13:] + alph[:13]
>>> alph
'abcdefghijklmnopqrstuvwxyz'
>>> alphrot
'nopqrstuvwxyzabcdefghijklm'
>>> 

Look at the alphabet and how it's mapped:

     a b c d e f g h i j k l m n o p q r s t u v w x y z
     | | | | | | | | | | | | | | | | | | | | | | | | | |
     | | | | | | | | | | | | | | | | | | | | | | | | | |
     n o p q r s t u v w x y z a b c d e f g h i j k l m
 
The same is true capitals.

Now if you wanted to include other characters you (the sender ==
encrypting person) and the reader (== decrypting person) must agree
where to place these additional characters.  Since this is most of the
time not possible normally rot13 is only applied to characters in the
ASCII range.


I found it interesting to write a small Python solution on how to do a
caesar chiffre and came up with the following (rot13 encrypted):

qrs znxr_gnoyr (*netf):
    gnoyr = {}
    sbe ghc va netf:
        fgp, raqp, qvf = ghc
        nycu = ''.wbva(znc(pue, enatr(beq(fgp), beq(raqp)+1)))
        nycuebg = nycu[qvf:] + nycu[:qvf]
        gnoyr.hcqngr(qvpg(mvc(nycu, nycuebg)))
    erghea gnoyr

qrs znxr_gnoyr (*netf):
    gnoyr = {}
    sbe ghc va netf:
        fgp, raqp, qvf = ghc
        fga, raqa = beq(fgp), beq(raqp)
        jvqgu = raqa - fga + 1
        sbe p va enatr(fga, raqa + 1):
            gnoyr[pue(p)] = pue((p - fga + qvf) % jvqgu + fga)
    erghea gnoyr

qrs ebg_a (frd, goy):
    erghea ''.wbva(znc(ynzoqn p: goy.trg(p, p), frd))

qrs ebg13 (frd, goy = znxr_gnoyr(('n', 'm', 13), ('N', 'M', 13))):
    erghea ebg_a(frd, goy)



There are two alternative functions to generate a table; that table is
used to find a substitution for a character in the rot13 function.  You
could add in that table mappings for additional characters if you liked.


   Karl
-- 
Please do *not* send copies of replies to me.
I read the list




More information about the Tutor mailing list