从字符串python 3.6中删除\n

too*_*oom 0 python string nslookup replace python-3.x

我试图从nslookup的输出中删除\n字符.虽然这看起来像一个简单的任务,但有许多关于过滤的帖子\n它们似乎对我不起作用.代码在Python 2.7中完美运行,但它不在3.6中

mx = str(subprocess.check_output(('nslookup -type=mx ' + "test.nl"), shell=True))

clean = re.sub(r"\n", " ", mx)
clean2 = mx.replace("\n", " ")

print(clean)
print(clean2)
Run Code Online (Sandbox Code Playgroud)

产量

\nNon-authoritative answer:\ntest.nl\tmail exchanger
Run Code Online (Sandbox Code Playgroud)

想要结果

 Non-authoritative answer: test.nl\tmail exchanger
Run Code Online (Sandbox Code Playgroud)

这些都不起作用,但是当我删除'\'时,它会完美地过滤'n'.谁能告诉我我做错了什么?或者我如何才能达到想要的结果?

ps:知道这可能是重复的,我只是犯了一个愚蠢的错误,但是类似帖子中给出的解决方案对我不起作用.

小智 6

使用\n进行替换时,可以将其解释为python的换行符或Regex的换行符.

您可以使用原始字符串,因此Python不会解析\n:

clean = mx.replace(r"\n", " ")
Run Code Online (Sandbox Code Playgroud)

或者你可以逃避符号:

clean = mx.replace("\\n", " ")
Run Code Online (Sandbox Code Playgroud)