Christian K Christian K - 5 months ago 17
Python Question

Python substring won't work with number integer

So I am having trouble with the code in the way that it gives an error: "line 30, in
(ciphertextBinary[i])[x] = "0"
TypeError: 'str' object does not support item assignment".
I have no idea as to why this happens as all that I am doing is changing a subtext of a string and replacing it with a string. If you can come up with any solutions it would be much obliged as I have looked for answers for a while now but have had no success. Before I had this error:

if (textBinary[i])[x] == (pad[i])[x]:
(ciphertextBinary[i])[x] = "0"
elif (textBinary[i])[x] != pad[i][x]:
(ciphertextBinary[i])[x] = "1"


the code was not working and returned the input so I changed it to what I think would make it work but have come across this error instead.

string = ""
string2 = ""
length = 0
lenght2 = 0
pad = ""


string = input("Enter String To Encrypt: ")
string2 = input("Enter PAD: ")

length = len(string)
length2 = len(string2)

textBinary = list(string)
pad = list(string2)
ciphertextBinary = list(string)
ciphertext = list(string)

for i in range(0, length):
textBinary[i] = "{0:b}".format(ord(string[i]))
for x in range(0, len(textBinary[i])):
ciphertextBinary[i] = ciphertextBinary[i] + "a"

for i in range(0, length2):
pad[i] = "{0:b}".format(ord(string2[i]))

for i in range(0, length):
for x in range(0, len(textBinary[i])):
if (textBinary[i])[x] == (pad[i])[x]:
(ciphertextBinary[i])[x] = "0"
elif (textBinary[i])[x] != pad[i][x]:
(ciphertextBinary[i])[x] = "1"

for i in range(0, length):
ciphertext[i] = int(ciphertextBinary[i], 2)
print(chr(ciphertext[i]))

Answer

Python does not let you change a single character within a string. Strings are considered an immutable type in Python just like numbers or tuples. Thus, your attempt to do string assignment within a string is somewhat like asking to change the third digit in the number 8435 to 0. Rather, you may be able to do something like this:

(ciphertextBinary[i]) = (ciphertextBinary[i])[:x] + "0" + (ciphertextBinary[i])[x+1:]

This works by setting your variable of interest equal to everything up to character x, plus the new character, plus all the characters that were after x.

I hope this helps.