Categories
Python Answers

How to remove the ANSI escape sequences from a string in Python?

Spread the love

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 can use the regex’s sub method.

For instance, we write:

import re

ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
sometext = 'ls\r\n\x1b[00m\x1b[01;31mexamplefile.zip\x1b[00m\r\n\x1b[01;31m'
s = ansi_escape.sub('', sometext)
print(s)

We call re.compile with a regex string that has the ANSI escape characters.

Then we have the sometext string that has some ANSI escape characters we want to remove.

To do that, we call ansi_escape.sub with an empty string and sometext to return a new string without the escape characters.

Therefore, s is:

ls
examplefile.zip

Conclusion

To remove the ANSI escape sequences from a string in Python, we can use the regex’s sub method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *