Reputation: 482
Anyone know how to do this?
Ex:
Replace sstring with sreplace in string s
s = "111sstring111"
expected output: "111sreplace111"
Upvotes: 0
Views: 1238
Reputation: 3973
Here's another option, but again it mostly just tests your python knowledge.
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
Upvotes: 3
Reputation: 49318
Here's another option using re.sub
, which is basically a more flexible str.replace
:
>>> import re
>>> s = "111sstring111"
>>> re.sub('sstring', 'sreplace', s)
'111sreplace111'
Upvotes: 2
Reputation: 113988
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
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
Upvotes: 3