python - 如何在不使用内置替换功能的情况下用另一个单词替换字符串中的单词?
问题描述
我正在尝试自己在 python 中重新创建“替换”功能,但我很难过。
我的函数需要三个输入,第三个字符串中第一个字符串的出现被第二个字符串替换。
例子:
replace("with", "by" , "Don't play without your friends")
Result: ("Don't play byout your friends")
到目前为止我尝试过这个,但它不起作用,我想我把它复杂化了。
def replace(s, s1, s2):
finall = list()
l1 = s2.split()
length_replace = len(s1)+1
newlist = list()
for i in range(len(l1)):
if (s in l1[i]):
newlist = list(l1[i])
s = newlist[length_replace:]
s = ''.join(s)
final = s1 + s
l1[i-1:i+1]= [final]
return l1
任何帮助表示赞赏。
解决方案
假设最多只出现一次,我会这样做:
def replace(source, match, replacing):
result = None
for i in range(0, len(source) - len(match)):
if source[i:i+len(match)] == match:
result = source[:i] + replacing + source[i+len(match):]
break
if not result:
result = source
return result
replace("Don't play without your friends", "with", "by")
# "Don't play byout your friends"
对于不止一次出现,您可以递归地编写它并提醒您source
或包含一些临时变量来存储先前迭代的聚合结果,例如:
def replace(source, match, replacing):
result = ''
i, j = 0, 0
while i < len(source) - len(match):
if source[i:i+len(match)] == match:
result += source[j:i] + replacing
i += len(match)
j = i
else:
i += 1
result += source[j:]
return result
replace('To be or not to be, this is the question!', 'be', 'code')
# 'To code or not to code, this is the question!'
replace('To be or not to be, this is the question!', 'is', 'at')
# 'To be or not to be, that at the question!'
并且只是为了看到它的行为类似于str.replace()
函数:
source = 'To be or not to be, this is the question!'
match = 'is'
replacing = 'at'
replace(source, match, replacing) == source.replace(match, replacing)
# True
推荐阅读
- java - 如何从字节数组中获取正确的温度值
- python - 读取文件中以 \n 结尾的行
- reactjs - 通过 map 函数打印渲染的组件之一
- xquery - 如何替换转换中的 $content 值?
- php - Ctrl + 单击不适用于 Visual Studio 代码
- docker - Docker-compose ps 显示带有目录前缀而不是项目名称前缀的 Docker 名称
- python - 在没有 GPS 的情况下绘制我的无人机的 3d 轨迹/路径
- c# - TextBlock中动态字符串的WPF本地化
- swift - 使用 Cocoapods 时 Generamba 设置失败
- asp.net-core-mvc - 添加到用户的角色确实在 IsInRole 中给出错误