Damian Abbott Damian Abbott - 2 years ago 75
Python Question

Getting parsed data from website with \frac and \sqrt how would i replace these with what they are in a string

I am getting strings from a website regarding mathematical equations, when there is a fraction the string it return is '\frac{number1}{number2}'

What I want to do is replace the \frac{}{} and make it for example from '\frac{1}{2}' to '(1)/(2)'

I assumed that re.groups would help with this and tried

>>> import re
>>> s = '\\frac{1}{2}'
>>> print(s)

>>> m = re.match(r'\frac{(\w+)}{(\w+)}',s)
>>> m.groups()
('1', '2')

>>> f = s.replace('\\frac{{}}{{}}'.format(m.group(1), m.group(2)), '{}{}{}{}{}'.format('(', m.group(1), ')/(', m.group(2), ')'))
>>> print(f)

I still get \frac{1}{2}

Am I going about this all wrong? Or is there an easier way to do this, or did I make a mistake? I cannot figure it out whatsoever

Also sometimes there is more than one in a string such as

'\frac{1}{2}\sqrt{3} + 3\frac{1}{3}'

Just trying to replace those parts of the string with a more readable version

Answer Source

Let's leverage the re.sub function, which will replace all matches in the string.

For the \frac case, let's use the following as are regex pattern:

patt = r'\\frac\{(\w+)\}\{(\w+)\}'

We have to escape the leading \ in front of frac, and { and } are metacharacters, so we escape those, too.

So we can now just do parsed_s = re.sub(patt, r'(\1)/(\2)', s) where s is the source string. This will replace all of the matches in the string with the desired format.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download