def replacest1(string, st1, st2):
return string.replace(st1, st2)
Test:
replacest1("abcdefdcba", "c", "x")
results in:
"abxdefdxba"
Test:
replacest1("yyyyzzzz", "c", "x")
results in:
"yyyyzzzz"
Or much much much much better:
"abcdefdcba".replace("c", "x")
Please note that the function defined above is a 1:1 correspondence to the function demanded by the question. It is not a good practice to use string
as an identifier. I'd strongly recommend not to use such kind of identifier.
A note: As the definition of such a function can be eliminated altogether as string.replace()
still exists while it is deprecated the solution above will still contain the identifier string
as used in the question. If the function couldn't be eliminated I'd use a different identifier here but as defining an own function isn't necessary at all anyway I let this identifier be as it is for now.
Here is a variant of how to implement that without the usage of string.replace()
:
def replaceCharacters(inputString, findChar, replaceChar):
assert isinstance(inputString, str)
assert isinstance(findChar, str)
assert len(findChar) == 1
assert isinstance(replaceChar, str)
assert len(replaceChar) == 1
buffer = ""
for c in inputString:
buffer += replaceChar if c == findChar else c
return buffer
A note: I prefer to use asserts in order to detect programming errors. If performance is not a big issue in your use case these asserts don't cause any trouble but prevent accidentally misusing a function like this: If you accidentally pass wrong parameters the asserts will fail and give you feedback immediately.