SpartaSixZero SpartaSixZero - 4 months ago 31
Python Question

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

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 a SSH command and I want my string to only contain 'examplefile.zip'

What I can use to remove the extra escape sequences?

Answer

Delete them with a regular expression:

import re

ansi_escape = re.compile(r'\x1b[^m]*m')
ansi_escape.sub('', sometext)

Demo:

>>> import re
>>> ansi_escape = re.compile(r'\x1b[^m]*m')
>>> sometext = 'ls\r\n\x1b[00m\x1b[01;31mexamplefile.zip\x1b[00m\r\n\x1b[01;31m'
>>> ansi_escape.sub('', sometext)
'ls\r\nexamplefile.zip\r\n'
Comments