How do you substitute the Nth by a given regular expression pattern in python?

I had a need to replace Nth IP address in logs by a given IP address. This is how achieved in 
pythonic way. It may be useful to you as well. 

import re
mystr = '203.23.48.0 DENIED 302 449 800 1.1 302 http d.flashresultats.fr  10.111.103.202 GET GET - 188.92.40.78 'src = '1.1.1.1'replace_nth = lambda mystr, pattern, sub, n: re.sub(re.findall(pattern, mystr)[n - 1], sub, mystr)
mystr = replace_nth(mystr, '\S*\d+\.\d+\.\d+\.\d+\S*', src, 2)
print(mystr)

# It outputs:203.23.48.0 DENIED 302 449 800 1.1 302 http d.flashresultats.fr  1.1.1.1 GET GET - 188.92.40.78 

Comments