Python: replace "wrong" floats with integers inside a string

I am trying to replace all useless floats in a string(1.0, 2.0, etc.) using strong> integers . So I would turn the string like "15.0+abc-3"

into "15+abc-3"

. Do you know a way to do this?

Hope you get my idea. If you are not free to ask.

+3


source to share


2 answers


(?<=\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)

      

0


source


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

!

+1


source







All Articles