Tell me more ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

I have an unintelligible string of characters with a simple key: every letter's true value is the letter +2 in the alphabet. Example: A --> C ; M --> O.

I wrote a simple python function that accepts two arguments, a string and a dictionary. It then searches for a character in the string, finds that key in the dictionary, and then returns the key's value. Problem is, I have it looping through and so when it finds an 'a', it replaces it with a 'c', which then replaces that with an 'e', then a 'g', and so on. So at the end, I have a big string of As and Bs.

alphadict = {'a': 'b', 'b': 'c':, 'c': 'd'...}

codestring = "dj afioj asfd sfijiojj ddk weic."

def replace_all(text, dic):
for i, j in dic.iteritems():
    text = text.replace(i, j)
return text

newtext = replace_all(codestring, alphadict)
print newtext

Can anyone help me figure out how to generate the function to replace a character once, then move on to the next without looping back through?

share|improve this question
2  
This is not a codegolf question. You should have posted it to stackoverflow.com. As regards your question, see docs.python.org/library/string.html#string.maketrans – Steven Rumbalski Aug 23 '11 at 15:41
Sorry, Steven. Thought I found the right place. Thanks for the redirect. – Robert Ray Aug 23 '11 at 19:23

closed as off topic by J B, boothby, dmckee Sep 23 '11 at 15:38

Questions on Programming Puzzles & Code Golf Stack Exchange are expected to relate to programming puzzle or code golf within the scope defined in the FAQ. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about closed questions here.

2 Answers

Here's a quick way to implement your replace_all function:

def replace_all(text, dic):
    return "".join([dic[c] for c in text])
share|improve this answer

What you're looking for is a ROT-N (2 in this case) function:

def rot2(str):
    chars = 'abcdefghijklmnopqrstuvwxyz'
    trans = chars[2:] + chars[:2]
    rot = lambda x : trans[chars.find(x)] if chars.find(x) > -1 else x
    return ''.join(rot(c) for c in str)

Similarly rot24() for going back to the original.

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.