Basically I've been trying to make a Caesar Cipher type program,
caesar=[
"x",
"y",
"z",
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
"q",
"r",
"s",
"t",
"u",
"v",
"w"
]
tempword=input('What would you like to encrypt? ')
list(tempword)
checklet=0
caesarlet=caesar[checklet]
for x in range(len(tempword)):
caeserlet=caesar[checklet]
tempword[checklet]=caesarlet
checklet=checklet 1
str(tempword)
print('Done encrypting, your word is: ',tempword)
but there always seems to be an error in this line:
tempword[checklet]=caesarlet
and heres the outputted error:
Traceback (most recent call last):
File "c:\Users\waisinz\Documents\python stuff\caesarcipher.py", line 35, in <module>
tempword[checklet]=caesarlet
TypeError: 'str' object does not support item assignment
I've already found some solutions to this on the site, but my puny brain was too smooth to understand any of them. Anybody know an easy fix, please?
CodePudding user response:
You are converting the string to a list, but you are not reassigning it. You should do:
tempword = list(tempword)
There is a better way to do this using the ord
and chr
. Code:
word = input("What would you like to encrypt? ")
word = list(word)
for index, letter in enumerate(word):
if ord(letter) - 3 < 97:
word[index] = chr(122 (ord(letter) - 2 - 97))
else:
word[index] = chr(ord(letter) - 3)
print(f"Done encrypting, your word is: {''.join(word)}")