Python: replace "wrong" floats with integers inside a string
(?<=\d)\.0+\b
You can just use that and replace with empty string
via re.sub
.
See demo.
https://regex101.com/r/hI0qP0/22
import re
p = re.compile(r'(?<=\d)\.0+\b')
test_str = "15.0+abc-3"
subst = ""
result = re.sub(p, subst, test_str)
source to share
You can use re.sub
:
>>> s="15.0+abc-3"
>>>
>>> import re
>>> re.sub(r'\b(\d+)\.0+\b',r'\1',s)
'15+abc-3'
>>> s="15.0000+abc-333.0+er1102.05"
>>> re.sub(r'\b(\d+)\.0+\b',r'\1',s)
'15+abc-333+er1102.05'
\d+
will match any digit of length 1 or more, and in the sub
function (\d+)\.0
will match numbers with a useless decimal zero. This will be replaced by the first group \1
that is your number (within the capture group (\d+)
).
And \b
- this is a word boundary that causes your regex to not match some numbers, like 1102.05
!
source to share