Sometimes, we want to remove the ANSI escape sequences from a string in Python.
In this article, we’ll look at how to remove the ANSI escape sequences from a string in Python.
How to remove the ANSI escape sequences from a string in Python?
To remove the ANSI escape sequences from a string in Python, we call the regex sub
method.
For instance, we write
def escape_ansi(line):
ansi_escape = re.compile(r"(?:\x1B[@-_]|[\x80-\x9F])[0-?]*[ -/]*[@-~]")
return ansi_escape.sub("", line)
to create the escape_ansi
function.
In it, we call re.compile
with a string to match all the ANSI escape characters.
And then we call ansi_escape.sub
to replace the matched values with empty strings in the line
string and return the string with the replacement done.
Conclusion
To remove the ANSI escape sequences from a string in Python, we call the regex sub
method.