Regex Using Python To Replace Dot Of Floating Numbers With "dot"
I want to replace '.' occurring in floating point numbers in my string with 'dot' and vice versa. Example: t=' I am coder. I work in Google. I earn 98748.85' Expected output: ' I a
Solution 1:
You're replacing the entire match with "dot", not just the dot.
I know of two ways of solving this:
1. Positive lookaround assertions:
re.sub(r'(?<=\d)\.(?=\d)',r"dot", t)
In this solution, you're only matching the dot itself, but assert that there is a number before and behind it.
2. Catching the numbers and replacing with the capture groups and dot:
re.sub(r'(\d+)\.(\d+)',r"\1dot\2", t)
Here you match the entire float, but remember the part before and after the dot in capture groups. You then change the replacement string to be "the first capture group, then the string 'dot', then the second capture group".
Post a Comment for "Regex Using Python To Replace Dot Of Floating Numbers With "dot""