0

I'm trying to use regex to replace instances of a fraction (specifically 1/2) with the decimal equivalent

string = "7 1/2"
re.sub(r'[1/2]', '.5', string)

Firstly, I think the above replaces all instances of 1, /, 2 with .5, whereas I'm trying to find and replace the entire term "1/2"

Secondly, how do you handle the leading space before the fraction itself?

3
  • "I think the above..." Have you tried or is this just speculation? Commented Dec 16, 2015 at 5:38
  • 1
    instead of [ ] use () to capture the fraction group Commented Dec 16, 2015 at 5:41
  • well when I try it on 7 1/2 I get 7 .5.5.5 so I believe its true in that case, just not sure if thats the generalized outcome Commented Dec 16, 2015 at 5:42

2 Answers 2

8

A general solution should be like below which should use a lambda function in the replacement part of re.sub.

>>> import re
>>> from __future__ import division
>>> s = "7 1/2"
>>> re.sub(r'(\d+)/(\d+)', lambda m: str(int(m.group(1))/int(m.group(2))), s)
'7 0.5'
>>> re.sub(r'(\d+)/(\d+)', lambda m: str(int(m.group(1))/int(m.group(2))), '7 9/2')
'7 4.5'

Update:

>>> re.sub(r'^(\d+)\s+(\d+)/(\d+)$', lambda m: str(float(int(m.group(1)) + int(m.group(2))/int(m.group(3)))), '7 9/2')
'11.5'
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, how would you add the converted fraction part back to the integer though? "7 1/2" should be "7.5" and "7 9/2" should be "11.5"
2

As an alternative to regex, if you always have a single number per string, and the fractional part is separated from the whole number part by whitespace, you could use the fractions module to perform a conversion:

from fractions import Fraction

for s in '7 1/2', '1 33/66', '22 21/22', '123', '123.45':
    f = sum(Fraction(x) for x in s.split())
    print(float(f))

Output

7.5
1.5
22.9545454545
123.0
123.45

Comments

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.