如何将列表中的项目从另一个列表中更改为另一个项目?

发布于 2025-02-06 15:00:23 字数 890 浏览 1 评论 0原文

基本上,我一直在尝试制作凯撒密码类型程序,

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)

但是这行似乎总有一个错误:

tempword[checklet]=caesarlet

而且,输出的错误:

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

我已经在网站上找到了一些解决方案,但是我的thim脑太光滑了,无法理解其中任何一个。有人知道一个简单的修复吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

怪我入戏太深 2025-02-13 15:00:23

您将字符串转换为列表,但您并没有重新分配字符串。您应该做:

tempword = list(tempword)

有一种更好的方法可以使用ORDchr进行此操作。代码:

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)}")

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)}")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文