def escapestring(s, replace={' ': '~', '$': '\\$', '&': '\\&', '#': '\\#',
    '_': '\\_', '%': '\\%', '^': '\\string^', '~': '\\string~', '<':
    '{$<$}', '>': '{$>$}', '{': '{$\\{$}', '}': '{$\\}$}', '\\':
    '{$\\setminus$}', '|': '{$\\mid$}'}):
    """Escapes ASCII characters such that they can be typeset by TeX/LaTeX"""
    i = 0
    while i < len(s):
        if not 32 <= ord(s[i]) < 127:
            raise ValueError('escapestring function handles ascii strings only'
                )
        c = s[i]
        try:
            r = replace[c]
        except KeyError:
            i += 1
        else:
            s = s[:i] + r + s[i + 1:]
            i += len(r)
    return s
