Jezza Halstead
Jezza Halstead

Reputation: 11

replacing a character by another character using chr and ord

I am trying to write a program that encrypts the text message entered by the user The program gets the ascii value of each character entered by the user and replaces the character with a character with ascii value three more than the original character For example, character with upper case 'A' (ascii - 65) is replaced by character 'D' (ascii - 68). I don't see how this can work. What should I do?

The sample outcome: Enter a message: This is a secret message

The encrypted message is: Wklv#lv#d#vhfuhw#phvvdjh1

I trying using the following code but it doesn't work with more than 1 string: char1 = 'A' char2 =(ord(char1)+3)

num1 = char2 print(chr(num1))

Upvotes: 1

Views: 490

Answers (1)

Adon Bilivit
Adon Bilivit

Reputation: 27196

Using ord and chr is one way to do this:

def encode(s):
    return ''.join(chr(ord(c)+3) for c in s)
print(encode('abc'))

Output:

def

Upvotes: 2

Related Questions