0

Say I have a string

string = "{1/100}"

I want to use regular expressions in Python to convert it into

new_string = "\frac{1}{100}"

I think I would need to use something like this

new_string = re.sub(r'{.+/.+}', r'', string)

But I'm stuck on what I would put in order to preserve the characters in the fraction, in this example 1 and 100.

4 Answers 4

2

You can use () to capture the numbers. Then use \1 and \2 to refer to them:

new_string = re.sub(r'{(.+)/(.+)}', r'\\frac{\1}{\2}', string)
# \frac{1}{100}

Note: Don't forget to escape the backslash \\.

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

Comments

2

Capture the numbers using parens and then reference them in the replacement text using \1 and \2. For example:

>>> print re.sub(r'{(.+)/(.+)}', r'\\frac{\1}{\2}', "{1/100}")
\frac{1}{100}

Comments

1

Anything inside the braces would be a number/number. So in the regex place numbers([0-9]) instead of a .(dot).

>>> import re
>>> string = "{1/100}"
>>> new = re.sub(r'{([0-9]+)/([0-9]+)}', r'\\frac{\1}{\2}', string)
>>> print new
\frac{1}{100}

1 Comment

There's no reason to restrict the arguments to numbers. \frac doesn't care what the two arguments are; it just typesets them, one above and one below the vincumulm.
0

Use re.match. It's more flexible:

>>> m = re.match(r'{(.+)/(.+)}', string)
>>> m.groups()
('1', '100')
>>> new_string = "\\frac{%s}{%s}"%m.groups()
>>> print new_string
\frac{1}{100}

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.