python - 从 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
解决方案
重构你的代码
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很好地描述了它是如何工作的。
推荐阅读
- javascript - 限制Vue材料芯片中的字符串长度
- arrays - PowerShell - .count() 不适用于字符串数组
- reactjs - React Navigation 5.x:跨材质顶部选项卡共享来自单个 API 调用的数据
- apache-spark - Spark google Bigquery 表数据框不返回任何行并且为空。但是,printSchema 返回元数据信息
- python - 如何按一列分组并获取另一列熊猫中的所有常见值
- javascript - 在Angular中触发消息事件后如何断开和连接socket.io
- javascript - Babylon.js 加载屏幕更改图像
- postgresql - 使用 Dart/Flutter Postgres 包存储日期和空日期需要两个单独的命令
- c - 何时以及如何在 sizeof 表达式中评估 VLA?
- reactjs - 获取 React 的开发版本以使用 NGINX 与后端通信