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?
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).
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...
text = text.replace(letter," "), you cannot use assignment with a string. Alsofor letter in text[1]is the same astext = text.replace(text[1]," ")