Teoman Yüksel Teoman Yüksel - 6 months ago 22
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


I wrote a little program:

word = input()

at = "AT"

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


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

3kt 3kt

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) ;)