任何人都知道如何做到这一点?Python:用另一个单词替换字符串中的某些单词?没有内置函数?
例:
替换sreplace sstring在字符串s
S = “111sstring111”
预期输出: “111sreplace111”
任何人都知道如何做到这一点?Python:用另一个单词替换字符串中的某些单词?没有内置函数?
例:
替换sreplace sstring在字符串s
S = “111sstring111”
预期输出: “111sreplace111”
replacement.join(s.split(target))
我猜...但它的可能不会帮助采访者掌握算法......它只会揭示你对python的掌握程度
re.sub(target,replacement,s) #would also work
,如果你正在寻找不使用内建你或许应该说,在这个问题
为什么-1?只是好奇? –
这里的算法是另一种选择,但同样大多只是测试你的Python知识。
index = theString.find(sstring)
if index != -1:
theString = theString[:index] + sreplace + theString[index + len(sstring):]
同样的想法,概括为一个以上的发生:
newString = ""
index = theString.find(search)
while index != -1:
newString = newString + theString[:index] + rep
theString = theString[index + len(sstring):]
index = theString.find(search)
newString += theString
下面是使用re.sub
另一种选择,这基本上是一个更灵活的str.replace
:
>>> import re
>>> s = "111sstring111"
>>> re.sub('sstring', 'sreplace', s)
'111sreplace111'
你为什么不能使用'str.replace'? – TigerhawkT3
电子白板/面试 –
当然,指派你完成这项任务的教师,a)给予讲座或b)分配一些阅读/视频或c)分配一本教科书或d)全部上述内容。是否有任何课程资源可供您用来开始执行此任务?然后,如果你的代码在某种程度上失败了,请回到一个特定的,经过深入研究的问题。 –