-1

Im new to python. I want to take an input from the console and encrypt it.I want to change the letters of the input string like this and then output.

a=e,
b=g,
c=p,
d=f,
e=i,
f=k,
g=q,
h=u,
i=h,
j=v,
k=z,
l=w,
m=j,
n=r,
o=d,
p=s,
q=t,
r=n,
s=c,
t=l,
u=y,
v=x,
w=b,
x=m,
y=o,
z=a

So If I input "Dog", it should output "Dog = Fdq" and If I input "python", it should output "python = soludr". How can I do this?

Suvin Nimnaka Sukka
  • 341
  • 1
  • 7
  • 21

2 Answers2

3

This is a good place to use dictionaries.

You can start by declaring your dictionary:

translateDict = {'a' : 'e', 
                 'b' : 'g',
                  #etc
                 'z' : 'a'}

Strings are effectively just lists of characters, in a lot of ways. You can therefore define a function that operates on each character:

def encryptWord(word):
    return ''.join([translateDict[x] for x in word])

What this is doing is using list comprehension. Effectively, the function makes a list of characters: specifically, for each character in your input word, it looks up its corresponding value in your dictionary, and (in order) creates a list out of those results. The join function creates a string by joining a list of characters or strings, adding the '' string between each one (in this case, not adding anything between each character).

This will cause problems if you put in a string that has letters not in your dictionary, but you should be able to work from that.

Taylor Nelms
  • 384
  • 2
  • 16
1

I agree the simplest way is by using dictionaries, see another example below:

    def encrypt(word):
    keys = {
        'a':'e',
        'b':'g',
        'c':'p',
        'd':'f',
        'e':'i',
        'f':'k',
        'g':'q',
        'h':'u',
        'i':'h',
        'j':'v',
        'k':'z',
        'l':'w',
        'm':'j',
        'n':'r',
        'o':'d',
        'p':'s',
        'q':'t',
        'r':'n',
        's':'c',
        't':'l',
        'u':'y',
        'v':'x',
        'w':'b',
        'x':'m',
        'y':'o',
        'z':'a'
    }

    encrypted_list = []
    for letter in word:
        encrypted_list.append(keys[letter])

    return ''.join(encrypted_list)

if __name__ == "__main__":
        text = input("Type the word you wanna encrypt: ")

        print(encrypt(str(text).lower()))

The example does not use list comprehensions intentionally since we already have another example with it.

Elder Santos
  • 309
  • 2
  • 11