TeachMeEverything
TeachMeEverything

Reputation: 158

Shifting characters up by 2. exploring python challenge part 2

I understand how this code works in python 2

import string

text = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp.\
        bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm\
        jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj`."

table = string.maketrans(string.ascii_lowercase,string.ascii_lowercase[2:]+string.ascii_lowercase[:2])
print text.translate(table)

Now I understand on python 3 that string was changed to str, bytes, bytesarray And I have solved it but with a way that seems a lot longer that simple maketrans without references.

How would that code be translated to python 3. trying to keep the maketrans method or not putting your a pre rendered table like 'abcde' to 'cdefg'.

But how would this be achieved in python 3 without making one yourself. or the simplest way of just shifting a character up by 2.(or if re/bitwise can do it)

I am really having fun with this, I'll take any input you can give and I will clarify if I was unclear.

My Python 3 code:

def decypher(cypher):
    dec=""
    for letter in cypher:
        if ord(letter)>=97 and ord(letter)<=122:
            dec+=chr((ord(letter)+2-97)%26+97)
        else:
            dec+=letter
    return dec

text="g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb.  lmu ynnjw ml rfc spj."

print(decypher(text))

Upvotes: 0

Views: 561

Answers (1)

Martin Tournoij
Martin Tournoij

Reputation: 27822

It seems that in Python 3 the maketrans() got moved to the str object and the translate() got removed, but since str.translate() already does the same we don't need it.

Your Python 2 code will work by simply changing the string.maketrans method call:

table = str.maketrans(
    string.ascii_lowercase,
    string.ascii_lowercase[2:] + string.ascii_lowercase[:2])

text = 'foo'
print(text.translate(table))

This is one of those somewhat arbitrary changes that makes migrating to Python 3 a little bit more difficult than it needs to be :-/

If you want your code to be compatible with both Python 2 and 3, you could use:

import string

maketrans = getattr(str, 'maketrans', getattr(string, 'maketrans', None))
table = maketrans(
    string.ascii_lowercase,
    string.ascii_lowercase[2:] + string.ascii_lowercase[:2])

print(text.translate(table))

P.S.

You can do the same without using translate and maketrans in two lines (or even one very long line, but that's ugly). I won't show you the code, but I encourage you to try and figure it out as a learning exercise! Hint: I used a dictionary. If you can't figure it out drop me a line and I'll give you another hint ;-)

Upvotes: 1

Related Questions