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

前端 未结 6 728
太阳男子
太阳男子 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:07

    Function

    Based on Martijn Pieters♦'s answer with Jeff's regexp.

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

    Test

    def test_remove_ansi_escape_sequence(self):
        line = '\t\u001b[0;35mBlabla\u001b[0m                                  \u001b[0;36m172.18.0.2\u001b[0m'
    
        escaped_line = escape_ansi(line)
    
        self.assertEqual(escaped_line, '\tBlabla                                  172.18.0.2')
    

    Testing

    If you want to run it by yourself, use python3 (better unicode support, blablabla). Here is how the test file should be:

    import unittest
    import re
    
    def escape_ansi(line):
        …
    
    class TestStringMethods(unittest.TestCase):
        def test_remove_ansi_escape_sequence(self):
        …
    
    if __name__ == '__main__':
        unittest.main()
    

提交回复
热议问题