import re


def formulafy(x):
    """
    Convert the input string x to a Latex representation of the chemical formula.
    e.g. ^13CH4 -> $^{13}CH_{4}$
    This can be used in matplotlib to display nicely a chemical formula.
    """
    return '$'+re.sub('([a-zA-Z])_?([0-9]+)', r'\1_{\2}', re.sub(r'\^([0-9]+)', r'^{\1}', re.sub('([\\+-]+)$', r'^{\1}', x)))+'$'