Centrum123 Centrum123 - 7 days ago 7
Python Question

Python String Type error

word = input("Please enter two words");
word1 = word
number = len(word);
space = '/'
for i in range(number):
if(word1[i] == " "):
word1[i] = space;
print(word1)


I am getting the following error: "TypeError: 'str' object does not support item assignment"
It doesn't like that I am replacing word1[i] = space;
I don't understand why because they are both strings.

Answer

Just as the error message says, you can't modify a string.

One approach, which will let you keep most of the code you've written, is to convert your string to a list of characters:

word = list(word)

Then join it back into a sting when you're done:

word = "".join(word)

Another approach is to build up a new string and conditionally choose which character is concatenated to it:

result = ""
for c in word:
    if c = " ":
        result += space    # should be named slash
    else:
        result += c

But a far better solution is to replace all that code with a single line:

word = word.replace(" ", "/")
Comments