def escape_latex(s):
    """ Escape characters that are special in latex
    http://stackoverflow.com/a/16264094/2570866"""
    CHARS = {
        '&':  r'\&',
        '%':  r'\%',
        '$':  r'\$',
        '#':  r'\#',
        '_':  r'\_',
        '{':  r'\{',
        '}':  r'\}',
        '~':  r'\~',
        '^':  r'\^',
        '\\': r'\\\\',
        '\n': r'\\',  # try to preserve newlines
    }

    return ("".join([CHARS.get(char, char) for char in s]))