triclosan
triclosan

Reputation: 5714

Lookahead assertion with dot

I need to remove trailing zeros from string represents floating point value x.xx

I try to use re.sub but no effect

re.sub("(?=\.[0-9])0", "", "1.23, 2.50, 2.00, 2.30, 5.03")

UPDATE

In my particular case there are only two digits after the dot. And I need to remove both zeros. With Ashwini Chaudhary and Porges help currently I use \.00|(?<=\.[0-9])0 probably better one expression exists. Remove zeros before point is not my goal.

Also would be interesting for me to see some general solution for various number of zeros not only for two.

Upvotes: 1

Views: 160

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250881

You should use lookbehind assertion not lookahead:

>>> re.sub("(?<=\.[0-9])0", "", "1.23, 2.50, 2.00, 2.30, 5.03")
'1.23, 2.5, 2.0, 2.3, 5.03'

(?<=\.[0-9])0

Regular expression visualization

Debuggex Demo

Upvotes: 4

porges
porges

Reputation: 30580

You want lookbehind, not lookahead. In your current expression \.[0-9] is trying to match at the same time as the 0, which will never happen.

Try: "(?<=\.[0-9])0"

Upvotes: 3

Related Questions