从python的字符串中删除两个不可打印的字符

问题描述 投票:0回答:2

我通过阅读单词文件得到如下文本

Exe Command\r\x07

我想要的文字是

Exe Command

我尝试过this solution,但它给了我

 Exe Command\r

如何删除2个反斜杠字符?我想要一个速度友好的解决方案,因为我有成千上万的输入。

python python-3.x string character-encoding backslash
2个回答
0
投票

您可以使用replace()方法两次。

In [1]: myStr.replace("\r", "").replace("\x07", "")
Out[1]: 'Exe Command'

如果这不起作用,您可以尝试使用原始字符串

In [1]: myStr.replace(r"\r", "").replace(r"\x07", "")
Out[1]: 'Exe Command'

-1
投票

您可以使用re模块,有点过大的杀伤力,但它也可以与连接了不需要字符的其他字符串匹配。

您将要匹配不需要的字符,然后使用re的子功能通过将它们替换为空字符串来删除它们。

>>> import re
>>>
>>> # store the string as a raw string 
>>> wrong_string = r'Exe Command\r\x07'  
>>>
>>> # compile the regex
>>> regex = re.compile(r'\\[\w]|[\d]')
>>>
>>> # use the sub method to replace the unwanted characters with ''
>>> wanted_string = re.sub(regex, '', wrong_string)
>>>
>>> wanted_string
'Exe Command'

正则表达式说明:

\-匹配文字字符\

[\ w] | [\ d] –匹配任何单词或数字

© www.soinside.com 2019 - 2024. All rights reserved.