I want to transform the string L^2 M T^-1 to L^2.M.T^-1. The dot replaces the space (\s) only if it is between two word characters. For example, if the string is 'lbf / s', no replacement will be applied.
str1= 'L^2 M T^-1'
pattern = re.compile(r'(\w+\s\w+)+')
def pattern_match2(m):
me = m.group(0).replace(' ', '.')
return me
pattern.sub(pattern_match2, str1) # this produces L2.MT-1
How can I replace the string with a dot (.) by repeated patterns?