3

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.

2 Answers 2

1

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!

Sign up to request clarification or add additional context in comments.

4 Comments

But it's only working with one 0 behind. Can you do one for infinite 0s?
@Unknown Yeah, just add + after 0. fixed!
I'm sorry I can't vote for both, but the other guy answered that faster :/ Thank you anyway.
@Unknown It's OK buddy! don't care about this imaginary points!
0
(?<=\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)

3 Comments

Thank you, but the other one was a bit faster :P
@Unknown there is it capturing a group which we dont need.
But both are only working, with number with only one 0 behind. Do one for infinite 0s, and you're the winner ^^ EDIT: Got it my self. You'll get the vote anyway for giving the link :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.