0

(Python 3.5) Is there a way to change an letter (from user input) into a different letter? This would work like an encryption program. The user would write, "Hello" and the program would print, "Gwkki."

H = "G"
e = "w"
l = "k"
o = "i"
q = input("Message: ")
print (q[0:4])
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Aavatar
  • 3
  • 1
  • Welcome to Stack overflow. Yes. You could e.g. use a caesar cipher, where you shift all letters by a given number of steps in the alphabet. Google that and you'll find examples. You'd assign the 'hello' to a string, then step through the string with e.g. a for loop to apply your cipher by attaching the shifted character to an empty string, one after another. – roadrunner66 Apr 24 '16 at 05:43

3 Answers3

1

yes you can simply use str.translate like this

text = input('Enter your text: ')

_in = "helo"
out = "Gwki"

print(text.translate(text.maketrans(_in, out)))

just like the name says, it "translates"(substitutes) each letter from your text found in your text in _in to the corresponding value in out

danidee
  • 9,298
  • 2
  • 35
  • 55
0

If you have a set way to convert the letters you could easily make a conversion function that you will pass the input in and it'll convert to necessary letters and return it.

Ex:

Hello passed into a function becomes Gwkki Olleh will become ikkwg and so on.

Lota
  • 1
  • 2
0

Say that the input string is stored in inputs and that you want to encode it without builtins and string methods?

transl = {'a':'W', ...}
encryp = ''
for e in (transl[c] for c in inputs): encryp += e

If a string method (not applied directly to inputs) is allowed

transl = {'a':'W', ...}
encryp = ''.join(transl[c] for c in inputs)

In both cases we use a dict to do the translation, constructing a sequence of encoded characters; to join these characters we can use a for loop and string concatenation (the + operator) or, in more idiomatic and efficient way, join them using the null string and its method .join()


Of course, the right way to proceed is using .translate(), as shown in danidee's answer.

Community
  • 1
  • 1
gboffi
  • 22,939
  • 8
  • 54
  • 85