Teoman Yüksel Teoman Yüksel - 3 months ago 10
Python Question

how to write a function, it will do the same thing with replace()

Can I define a function, that will do the same thing with

string.replace(old,new)
?

I wrote a little program:

word = input()


at = "AT"

if at in word:
new = word.replace(at,"IN")

print(new)


However I don't want to use the
replace()
, I want to use a custom function.

3kt 3kt
Answer

Take a look at this :

def custom_replace(string, old, new):

    index = string.find(old)

    if index == -1:
        return string

    return string[:index] + new + string[index + len(old):]


string = 'Hello World !'

old = 'World'
new = 'StackOverflow'

print(custom_replace(string, old, new))

Which outputs :

Hello StackOverflow !

Hope it'll be helpful (and that find is authorized) ;)