MetallicPriest
MetallicPriest

Reputation: 30765

How do I properly use the sub function of regular expression in Python?

So I have a number like 7.50x, which I want to convert to 7.5x. I thought about using regular expressions. I can easily match this expression, for example by using re.search('[0-9].[0-9]0x', string). However, I'm confused how to replace every such number using the re.sub method. For example what should be there as the second argument?

re.sub('[0-9].[0-9]0x', ?, string)

Upvotes: 0

Views: 2191

Answers (3)

Avinash Raj
Avinash Raj

Reputation: 174736

Using positive lookahead and lookbehind assertion.

>>> import re
>>> num="7.50x"
>>> re.sub(r'(?<=\d\.\d)0(?=x)', r'', num)
'7.5x'
  • (?<=\d\.\d), the number which precedes the digit 0 would be in this digit dot digit format.
  • And the character following the match (0) must be x

  • \. Matches a literal dot.

Upvotes: 1

nu11p01n73R
nu11p01n73R

Reputation: 26667

re.sub(r'([0-9]\.[0-9])0x', r'\1x', num)

Test

>>> import re
>>> num="7.50x"
>>> re.sub(r'([0-9]\.[0-9])0x', r'\1x', num)
'7.5x'
  • r'\1x' here \1 is the value saved from the first capturing group, ([0-9]\.[0-9])

    eg for input 7.50x the capturing group matches 7.5 which saved in \1

Upvotes: 2

vks
vks

Reputation: 67968

0+(?![1-9])(?=[^.]*$)

Try this.See demo.

http://regex101.com/r/hQ9xT1/14

x=7.50x
re.sub(r"0+(?![1-9])(?=[^.]*$)","",x)

Upvotes: 1

Related Questions