Teoman Yüksel Teoman Yüksel - 1 year ago 57
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
Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download