-1
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!?."
list = []

msg = 'Hello World'
key = input()
key = int(key)
print(alphabet[key])

for x in msg:
  list.append(x)
  
print(list)

So basically i need to replace each letter of my array to a specify position (given by the key) of my string. e.g. key = 3 so H becomes L , E becomes I , L becomes P etc... it's basically a Caesar cipher

ILS
  • 1,224
  • 1
  • 8
  • 14

4 Answers4

0
from collections import deque

alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!?. "

msg = 'Hello World'
key = int(input()) #3

new_alphabet = deque([i for i in alphabet])
new_alphabet.rotate(key)

new_message_list = [new_alphabet[alphabet.index(m)] for m in msg]
print("".join(new_message_list))  # Ebiil!Tloia
uozcan12
  • 404
  • 1
  • 5
  • 13
  • in a regular caesars cipher the shift direction is from left to right for a positiv number as key. deque.rotate(n) is shifting in the other direction from right to left. to change shift direction, place a ````-```` in front of the key numer – lroth Oct 03 '22 at 19:02
0

Hello, maybe one of these 2 Solutions will help you:

# Solution 1 using the ASCII table as base:
msg = 'Hello World'
key = int(input())
res = ''

for letter in msg:
    res += ''.join(chr(ord(letter) + key))    # ord(letter) gets the ascii value of the letter. then adding the key and chr() trandforming back from ascii value to character

print(res)


# Solution 2 using your alphabet as base
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!?."

msg = 'Hello World'
key = int(input())
res = ''

for letter in msg:
    try:
        position = alphabet.index(letter) + key # get the index position of each letter and adding the key
        char_new = alphabet[position]
    except ValueError:  # handels cases where characters are used, that are not defined in alphabet
        char_new = ' '
    res += ''.join(char_new)  # joins the new position to the result

print(res)
Michael
  • 15
  • 5
0

a space has been added to the end of alphabet to handle spaces in input.

alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!?. "
lst = []
msg = 'Hello World'
key = int(input('enter key number: '))

for x in msg:
      lst.append(alphabet[(alphabet.index(x) + key) % len(alphabet)])
print(''.join(lst))
lroth
  • 367
  • 1
  • 2
  • 4
0
import string

alphabet=[i for i in string.ascii_uppercase] 

key=int(input("Enter key: ")) 
msg=input("Enter plain text message:").upper()
enc=[] 

for i in msg:   
    
    if i == " " or i in string.punctuation: 
        enc.append(i)
    
    if i in alphabet:
        enc.append(alphabet[(alphabet.index(i)+key)%len(alphabet)])
        
print("Encrypted message is:"+"".join(enc)) 
j.b
  • 1
  • 1
  • the string.punctuation is to handle ponctuation like ()[]{}!@#$% and some other characters – j.b Oct 03 '22 at 19:33