[英]Python: Replace certain words in string with another word? Without built in functions?
Anyone know how to do this? 有人知道怎么做吗?
Ex: 例如:
Replace sstring with sreplace in string s 用s中的sreplace替换sstring
s = "111sstring111" s =“ 111sstring111”
expected output: "111sreplace111" 预期输出:“ 111sreplace111”
replacement.join(s.split(target))
i guess ... but its probably not going to help the interviewr with your grasp of algorithms ... it would only reveal your grasp of python 我猜...但是它可能不会帮助面试官掌握算法...它只会揭示您对python的掌握
re.sub(target,replacement,s) #would also work
if you are looking for an algorithm that uses no builtins you should probably say that in the question 如果您正在寻找不使用内建函数的算法,则可能应该在问题中这样说
Here's another option, but again it mostly just tests your python knowledge. 这是另一种选择,但同样,它大多只是测试您的python知识。
index = theString.find(sstring)
if index != -1:
theString = theString[:index] + sreplace + theString[index + len(sstring):]
Same idea, generalized for more than one occurrence: 相同的想法,适用于多次出现:
newString = ""
index = theString.find(search)
while index != -1:
newString = newString + theString[:index] + rep
theString = theString[index + len(sstring):]
index = theString.find(search)
newString += theString
Here's another option using re.sub
, which is basically a more flexible str.replace
: 这是另一个使用
re.sub
的选项,它基本上是更灵活的str.replace
:
>>> import re
>>> s = "111sstring111"
>>> re.sub('sstring', 'sreplace', s)
'111sreplace111'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.