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.
    """
    import re
    return '$' + re.sub('([a-zA-Z])_?([0-9]+)', '\\1_{\\2}', re.sub(
        '\\^([0-9]+)', '^{\\1}', re.sub('([\\+-]+)$', '^{\\1}', x))) + '$'
