如何用索引替换python上的列表项

如何用索引替换python上的列表项,python,list,encryption,indexing,Python,List,Encryption,Indexing,无论出于何种原因(我应该使用JS),我都在使用Python创建加密/解密程序。在加密程序中,空格是胡萝卜(^)。在解密程序中,我有: msg = raw_input("Msg: ") dmsg = list(msg) for i in dmsg: if i == "^": dmsg[i] = " " print dmsg 当给定字符串“^^^”时,输出为。。。“TypeError:列表索引必须是整数,而不是Unicode”。我要找的只是一个函数或语句 for i in

无论出于何种原因(我应该使用JS),我都在使用Python创建加密/解密程序。在加密程序中,空格是胡萝卜(^)。在解密程序中,我有:

msg = raw_input("Msg: ")
dmsg = list(msg)
for i in dmsg:
    if i == "^":
        dmsg[i] = " "
print dmsg
当给定字符串“^^^”时,输出为。。。“TypeError:列表索引必须是整数,而不是Unicode”。我要找的只是一个函数或语句

for i in dmsg:
此代码是列表中所有元素的迭代,而不是索引。

尝试将replace用作字符串。不需要转换为列表

msg = raw_input("Msg: ")
dmsg = msg.replace('^',' ')

关注你所犯的错误

您可以使用字符作为列表索引,如果您需要更改应该使用的字符串


您正在迭代list元素,但稍后您将使用该元素作为索引,其中需要一个整数。 看起来你想要的应该如下

msg = raw_input("Msg: ")
dmsg = list(msg)
for i in range(len(dmsg)):
    if msg[i] == "^":
        dmsg[i] = " "
print dmsg

更好的方法可以使用
str.replace
方法

msg = raw_input("Msg: ")
dmsg = msg.replace('^', ' ')
请这样做

for i in range(len(dmsg)):
    if i == "^":
        dmsg[i] = " "

我使用的是windows 10,而我使用的是IDLEWindows 10,它对IDLE的支持非常好。
I
不是
dmsg
的索引。请考虑一下在for循环中迭代的内容。你的错误应该会变得清楚。虽然这可能会回答问题,但是一些关于如何以及为什么这样做的评论和/或解释会很好。这也将帮助其他用户。
msg = raw_input("Msg: ")
dmsg = msg.replace('^', ' ')
for i in range(len(dmsg)):
    if i == "^":
        dmsg[i] = " "