如何从python中的字符串中删除ANSI转义序列 [英] How can I remove the ANSI escape sequences from a string in python
本文介绍了如何从python中的字符串中删除ANSI转义序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的字符串:
'ls\r\\\
\x1b [00m\x1b [01 ; 31mexamplefile.zip\x1b [00m\r\\\
\x1b [01; 31m'
我正在使用代码从SSH命令中检索输出,而且我希望我的字符串只包含'examplefile.zip'$ /
我可以用来删除额外的转义序列?
解决方案
使用正则表达式删除它们:
import re
ansi_escape = re.compile(r'\x1b [^ m] * m')
ansi_escape.sub('',sometext )
演示:
>>> import re
>>> ansi_escape = re.compile(r'\x1b [^ m] * m')
>>>> sometext ='ls\r\\\
\x1b [00m\x1b [01; 31mexamplefile.zip\x1b [00m\r\\\
\x1b [01; 31m'
>> ;> ansi_escape.sub('',sometext)
'ls\r\\\
examplefile.zip\r\\\
'
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?
解决方案
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'
这篇关于如何从python中的字符串中删除ANSI转义序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文