How to replace a character in some specific word in a text file using python
Question: I got a task to replace "O"(capital O) by "0" in a text file by using python.
But one condition is that I have to preserve the other words like Over, NATO
etc. I have to replace only the words like 9OO to 900, 2OO6 to 2006 and so on.
I tried a lot but yet not successful. My code is given below. Please help me
any one. Thanks in advance

    
    
    import re
    
    srcpatt = 'O'
    rplpatt = '0'
    cre = re.compile(srcpatt)
    
    with open('myfile.txt', 'r') as file:
        content = file.read()
    
    wordlist = re.findall(r'(\d+O|O\d+)',str(content))
    print(wordlist)
    
    for word in wordlist:
        subcontent = cre.sub(rplpatt, word)
        newrep = re.compile(word)
        newcontent = newrep.sub(subcontent,content)
    
    with open('myfile.txt', 'w') as file:
        file.write(newcontent)
    
    print('"',srcpatt,'" is successfully replaced by "',rplpatt,'"')
    


Answer: `re.sub` can take in a replacement function, so we can pare this down pretty
nicely:

    
    
    import re
    with open('myfile.txt', 'r') as file:
        content = file.read()
    with open('myfile.txt', 'w') as file:
        file.write(re.sub(r'\d+[\dO]+|[\dO]+\d+', lambda m: m.group().replace('O', '0'), content))
    

