How can I remove the ANSI escape sequences from a string in python

前端 未结 6 611
太阳男子
太阳男子 2020-11-22 14:26

This is my string:

\'ls\\r\\n\\x1b[00m\\x1b[01;31mexamplefile.zip\\x1b[00m\\r\\n\\x1b[01;31m\'

I was using code to retrieve the output from

6条回答
  •  有刺的猬
    2020-11-22 15:09

    If it helps future Stack Overflowers, I was using the crayons library to give my Python output a bit more visual impact, which is advantageous as it works on both Windows and Linux platforms. However I was both displaying onscreen as well as appending to log files, and the escape sequences were impacting legibility of the log files, so wanted to strip them out. However the escape sequences inserted by crayons produced an error:

    expected string or bytes-like object
    

    The solution was to cast the parameter to a string, so only a tiny modification to the commonly accepted answer was needed:

    def escape_ansi(line):
        ansi_escape = re.compile(r'(\x9B|\x1B\[)[0-?]*[ -/]*[@-~]')
        return ansi_escape.sub('', str(line))
    

提交回复
热议问题