Search code examples
pythonlatex

Python Latex Library


I often work with groups of materials and my file/materials are named as alphanumeric strings. Is there a library to turn a string like r"Mxene - Ti3C2" to latex styled r"Mxene - Ti$_\mathrm{3}$C$_\mathrm{2}$"?

I usually use a dictionary but going through every name is a hassle and prone to error because materials can always be added or removed from the study.

I know that I can use str.maketrans() to generate subscripts but I haven't had very consistent results using the output with matplotlib so I'd much rather use latex.


Solution

  • I've ultimately created this solution in case anyone else needs it. Since my problem is mostly to create subscripts, the following code will look for numbers and replace them with a latex equivalent to create one.

    def latexify(s):
    
        import re
        nums = re.findall(r'\d+', s)
        pos = [[m.start(0), m.end(0)] for m in re.finditer(r'\d+', s)]
        numpos = list(zip(nums, pos))
    
        for num, pos in numpos:
            string = f"$_\mathrm{{{num}}}$"
            s = s[:pos[0]] + string + s[pos[1]:]
            
            for ind, (n, [p_st, p_end]) in enumerate(numpos):
                if p_st > pos[1]:
                    numpos[ind][1][0] += len(string)-len(num)
                    numpos[ind][1][1] += len(string)-len(num)
                
                pass
            
        return s
    
    latexify("Ti32C2")
    

    Returns:

    'Ti$_\\mathrm{32}$C$_\\mathrm{2}$'