5
def remove_char(text):
    for letter in text[1]:
        text[0] = text[0].replace(letter," ")
    return text[0]

This is returning:

'str' object does not support item assignment

Why? And how can I make this work?

2
  • 3
    text = text.replace(letter," "), you cannot use assignment with a string. Also for letter in text[1] is the same as text = text.replace(text[1]," ") Commented Jul 26, 2016 at 22:54
  • 1
    The exception in other words: A python string is immutable.. Commented Jul 26, 2016 at 22:54

3 Answers 3

5

In Python, strings are not mutable, which means they cannot be changed. You can, however, replace the whole variable with the new version of the string.

Example:

text = ' ' + text[1:] # replaces first character with space
Sign up to request clarification or add additional context in comments.

Comments

2

Strings are immutable. By trying:

text[0] = text[0].replace(letter," ")

you are trying to access the string and change it, which is disallowed due to the string's immutability. Instead, you can use a for loop and some slicing:

for i in range(0, len(y)):
    if y[i] == ",":
        print y[i+1:len(y)]
        break

You can change the string a variable is assigned to (second piece of code) rather than the string itself (your piece of code).

1 Comment

hmm, maybe I should have been more clear. The input (text) is a string that is separated by a comma. I want to remove all of the letters in the string on the left of the comma when the characters in the string in the right side of the comma appear.
0

Assuming that the parameter text is a string, the line for letter in text[1]: doesn't make much sense to me since text[1] is a single character. What's the point of iterating over a one-letter string?

However, if text is a list of strings, then your function doesn't throw any exceptions, it simply returns the string that results from replacing in the first string (text[0]) all the letters of the second string (text[1]) by a blank space (" ").

The following examples show how remove_char works when its argument is a list of strings:

In [462]: remove_char(['spam', 'parrot', 'eggs'])
Out[462]: 's  m'

In [463]: remove_char(['bar', 'baz', 'foo'])
Out[463]: '  r'

In [464]: remove_char(['CASE', 'sensitive'])
Out[464]: 'CASE'

Perhaps this is not the intended behaviour...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.