0

I am currently debugging a function that returns a string that has a specific substring removed. I am not using any shortcuts (e.g. remove_all method); my aim is to keep the idea of this function and only fix the errors.

I have tried slicing the string by skipping the length of substring, but it does not fix the issue.

def remove_substring(string, substring):
    p = string.find(substring)
    # p is the next position in the string where the substring starts
    lsub = len(substring)
    while p >= 0:
        string[p : len(string) - lsub] = string[p + lsub : len(string)]
        p = string.find(substring)
    return string

Whenever I run the function, it gives a TypeError: 'str' object does not support item assignment

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
rrr
  • 361
  • 4
  • 13
  • You are missing the argument from your method definition. Change it to `def remove_substring(string, substring):` – jarthur Aug 29 '19 at 01:05
  • 1
    Possible duplicate of ['str' object does not support item assignment in Python](https://stackoverflow.com/questions/10631473/str-object-does-not-support-item-assignment-in-python) – hek2mgl Aug 29 '19 at 01:43

2 Answers2

1

You need to regenerate the str instead of attempting to modify it:

def remove_substring(string, substring):
    lsub = len(substring)
    while True:
        # p is the next position in the string where the substring starts
        p = string.find(substring)
        if p == -1:
            break
        string = string[:p] + string[p+lsub:]
    return string

print(remove_substring('foobarfoobar', 'bar'))
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
0

Str is a data type which can not be modified in Python. You should reset whole value instead of modifying by index.

string = string[:p] + string[p+lsub:]
Edward
  • 1
  • 1
  • 1