简体   繁体   中英

Python: Replace “wrong” floats by integers inside string

I'm trying to replace all useless floats in a string (1.0, 2.0 etc.) by integers . So I'd turn a string like "15.0+abc-3" to "15+abc-3" . Do you know a way to do that?

I hope you understood my idea. If you didn't feel free to ask.

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 with length 1 or more and in sub function (\\d+)\\.0 will match the numbers with useless decimal zero.that will be replaced by the first group \\1 that is your number (within capture group (\\d+) ).

And \\b is word boundary that makes your regex doesn't match some numbers like 1102.05 !

(?<=\d)\.0+\b

You can simple use this and replace by 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM