-1

Not sure if the title makes sense or really how to word the question, but what I am trying to have done is the user inputs a sentence per-say, and then it will grab from the other string according to whatever index that letter is and print it to the new string then print the string.

Probably a simpler way, but if you could explain this way and the easier one that would cool maybe you will understand once you see the code.

abc = "abcdefghijklmnopqrstuvwxyz"
caesar_cipher="bcdefghijklmnopqrstuvwxyza"
user = input("Enter what you want ciphered: ")
new_string = ''




print(new_string)
Blue
  • 243
  • 1
  • 8
  • 26

2 Answers2

5

Use str.translate and str.maketrans:

new_string = user.translate(str.maketrans(abc, caesar_cipher))

For example:

>>> "hello, world".translate(str.maketrans(abc, caesar_cipher))
'ifmmp, xpsme'
ForceBru
  • 43,482
  • 10
  • 63
  • 98
1

I think what you want is to implement the Caeser cipher. If you observe what a Ceaser cipher is, it just shifts each character by a fixed number of characters. In your example, all 'a's are replaced by 'b's, 'b's by 'c's, and so on. Just the basic version with your example can be done like this:

def encode_using_ceaser_cipher(input):
    output = ''
    for c in input:
        output += chr((ord(c) + 1)% (26 + 97))
    return output


    abc = "abcdefghijklmnopqrstuvwxyz"
    user = input("Enter what you want ciphered: ")
    new_string = encode_using_ceaser_cipher(input)
    print(new_string)

To understand what this line does

output += chr((ord(c) + 1)% (26 + 97))

We are converting the character stored in c to its ascii value, incrementing it by 1, and then converting it back to a character by using chr. Converting 'z' back to a character this way, however, will result in getting a character that is not in the [a-z] range. To do that, we had to do this ugly hack of a modulus operator. NOTE: This would only work for small letters (a-z). Hope this helps.

mazeman
  • 23
  • 5