Python Challenge [1]

It’s Python Challenge Day 2 and we’re off and rolling with strings! The title gives a solid direction for this one.

From the image, it seems like we probably ought to be shifting letters. All three examples move the letter 3 places further in the alphabet, so it would seem we have a consistent translation. Since we mentioned the helpful title, let’s google ‘python make trans’ and see what comes up.

First thing that the results show is that there is indeed a function called ‘maketrans()’ and it is part of the ‘string’ library. To get access to that library, we start things off with an import statement:

import string

There are a ton of useful functions in the String library and since it’s always a good idea to get used to browsing provided documentation, I’ll just leave the link.

If you browse down to String Functions, you’ll see the function string.maketrans() with the arguments “from” and “to”. Since we can put variable in for these arguments, let’s see if there is anything else that might be useful in the String library.

I’m not a fan of writing out things like an alphabet, and I see we have a string.lowercase() function. Our sample text is all in lowercase, but we might want to use this again, so I’d rather over-engineer the script a little. We also have string.letters() available, but since it concatenates string.uppercase() string.lowercase() we won’t be able to shift both cases conveniently. So we create our own version of string.letters() with a string shift to move our alphabet two letters down the line. With string functions, I tend to think of the pointers in brackets as the [where-do-ya-wanna-start:where-do-ya-wanna-end]

First, we’ll create our lowercase shift

alphabet_lower = string.lowercase[2:]+string.lowercase[:2]

Then, we’ll create our uppercase shift

alphabet_upper = string.uppercase[2:]+string.uppercase[:2]

And concatenate them

code = alphabet_lower + alphabet_upper

Now we need use maketrans() to build a translate() function.

translation = string.maketrans(string.letters, code)

Copy the target text to a variable (‘text’), then we can run

print text.translate(translation)

and we have our clue for the next level.