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

2
  • You are missing the argument from your method definition. Change it to def remove_substring(string, substring): Commented Aug 29, 2019 at 1:05
  • 1
    Possible duplicate of 'str' object does not support item assignment in Python Commented Aug 29, 2019 at 1:43

2 Answers 2

2

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'))
Sign up to request clarification or add additional context in comments.

Comments

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:]

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.