首页 > 解决方案 > 从 Python 中的另一个字符串中删除第一次出现的字符串

问题描述

我是一个完全的编程新手,我正在使用“如何像计算机科学家一样思考”来了解 Python。

我正在尝试编写一个函数,该函数将从另一个字符串中删除第一次出现的字符串,例如:remove("an", "banana") == "bana。目标不是使用内置方法,而是而是使用切片和索引技术来组成我自己的函数。

这是我迄今为止尝试过的:

def remove(substring, string):
    sublen = len(substring)
    new_string = "" 

    for i in range(len(string)): 
    #test if string slices are different from substring and if they are, add them to new_string 
    #variable
        if string[i:i+sublen+1] != substring:
            new_string += string[i:i+sublen+1]
    return new_string   

我遇到了另一个帖子,有人问了和我一样的问题(编写一个函数,从另一个字符串中删除第一次出现的字符串。),但我不明白所提供的解决方案应该如何工作。如果有人能指出我正确的方向,我将不胜感激,或者至少帮助理解我在这里缺少什么。

非常感谢您!

编辑感谢非常有用的评论,我了解如何重构我的代码以使其工作:

def remove(substring, string):
    sublen = len(substring)
    new_string = "" 

    for i in range(len(string)): 
        #find if slice of string and substring match.
        if string[i:i+sublen] == substring:
            #if true add slice and rest of string to new_string
            new_string += string[i+sublen:]
            break
        else:
             new_string += string[i] #add only the character = to loop 
                                     #variable
    return new_string   

标签: pythonstring

解决方案


重构你的代码

def remove(substring, string):
    sublen = len(substring)
    new_string = "" 

    for i in range(len(string)):

      if string[i:i+sublen] == substring:
          # found so append remaining string
          new_string += string[i+sublen:]
          break
      else:
          new_string += string[i]  # not found so append character

    return new_string 

print(remove("today", 'today is friday, the last friday of the month')) 

输出

is friday, the last friday of the month

替代解决方案(来自您的链接)

def remove(substring, string)
    return string.replace(substring, '', 1)

这使用替换函数来替换第一次出现的字符串。

Python 字符串 | replace很好地描述了它是如何工作的。


推荐阅读