简体   繁体   English

使用切片删除字符串的特定子字符串

[英]Removing specific substring of a string using slicing

I am currently debugging a function that returns a string that has a specific substring removed. 我目前正在调试一个函数,该函数返回已删除特定子字符串的字符串。 I am not using any shortcuts (eg remove_all method); 我没有使用任何快捷方式(例如remove_all方法); 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 每当我运行该函数时,它都会给出TypeError:'str'对象不支持项目分配

You need to regenerate the str instead of attempting to modify it: 您需要重新生成str而不是尝试对其进行修改:

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'))

Str is a data type which can not be modified in Python. Str是无法在Python中修改的数据类型。 You should reset whole value instead of modifying by index. 您应该重置整个值,而不是通过索引进行修改。

string = string[:p] + string[p+lsub:]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM