2

I'm playing around with a simple crypting program, and I want it to work so that every specific symbol, always will turn into another specific symbol. That might not be the best description, but I don't know how else to put it... For an example:

"a" is going to be "h"

"A" is going to be "k"

"h" is going to be "W"

text_1 = "aAh"

text_2 = text_1.replace('a', 'h')
text_3 = text_2.replace('A', 'K')
text_4 = text_3.replace('h', 'W')

print text_4

#the output is "WKW"
#I need the output to be "hKW"

The problem is, that I'm using the replace-command for every single symbol-replacement, so if we suppose that the codes are typed in the same order as our example, and the message I want to crypt is "aAh", then I would like the crypted output to be "hKW" but actually we get this output instead "WKW".

I know why this is happening, so my question is:

How do I get the program to crypt the message the way I intended it to do?

0

2 Answers 2

0

The problem you have is that you're applying your changes to intermediate strings (so the previous changes will affect the result)

Consider trying to calculate the intended changes on the initial string for each character and build the final string after.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use a dict for your character mapping and then use a generator expression to translate the characters:

m = {'a': 'h', 'A': 'K', 'h': 'W'}
print(''.join(m.get(c, c) for c in text_1))

This outputs:

hKW

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.