Lincoln Lincoln - 21 days ago 6
Python Question

How can you replace an item of list on python by index

For whatever reason (I should be using JS), I am using Python to create an encryption/decryption program. In the encryption program, spaces are carrots (^). In the decryption program I have:

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


When given the string "^^^", the output is... "TypeError: list indices must be integers, not unicode". Windows 10 doesn't support IDLE, so I'm using PyScripter. Is that the issue?

Answer

you are iterating over the list element, but later you are using the element as an index where you need an integer instead. seems like what you want should be as below

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

OR

msg = raw_input("Msg: ")
dmsg = list(msg)
for n,i in enumerate(dmsg):
    if i == "^":
        dmsg[n] = " "
print dmsg

better way can just use str.replace method

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