String is I wanted to replace the second occurrence of the dot with ‘_’.

str = "Hello. world. Hello!" 
x = re.sub(r'^((.){1}).', r'\1_', str)
#x = str.find(str.find('.')

The output I am getting is ‘H_llo. world. Hello!’. What should be the correct solution


With your shown samples, could you please try following. Written and tested in Python3.8

import re
str1 = "Hello. world. Hello!"
re.sub(r'^(.*?\.)([^.]*)\.(.*)$', r'\1\2_\3', str1)
'Hello. world_ Hello!'

Explanation: Simply importing re function of Python3.8 then creating str1 variable with value. Then using re.sub function to replace 2nd dot with _ as per requirement. In re.sub function on first argument giving regex to match everything apart from 2nd dot(in 3 capturing groups) and replacing them as per need with respective capturing groups placing _ on place of 2nd dot.

Explanation of regex:

^(.*?\.)  ##Creating 1st capturing group, where Matching till 1st dot from staring of value.
([^.]*)   ##Creating 2nd capturing group, matching just before dot(2nd dot) here.
\.        ##Matching exact literal dot here.
(.*)$     ##Matching/keeping everything else till last of value in 3rd capturing group.


172 2 2 0