1

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?

zoid_
  • 15
  • 4
  • the line `list(tempword)` returns a list (which you can then modify). However, your code isn't storing that list that was returned. Instead, it continues to use the string returned from `input(...)`. To fix this, change the line `list(tempword)` to `tempword = list(tempword)`. Or the previous line to `tempword = list(input(....))` – algrebe Jun 11 '22 at 03:18

1 Answers1

1

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)}")
KetZoomer
  • 2,701
  • 3
  • 15
  • 43