Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I change an item in a list to another item from another list?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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)}")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading