如何使用正则表达式删除制表符和换行符

Mar*_*lez 6 python regex python-3.x

在Python 3.x中,特殊重新序列'\ s'匹配Unicode空白字符,包括[\ t \n\r \n\f\v].

以下代码旨在用空格替换制表符和换行符.

import re
text = """Hello my friends.
    How are you doing?
I'm fine."""
output = re.sub('\s', ' ', text)
print(output)
Run Code Online (Sandbox Code Playgroud)

但是,选项卡仍然存在于输出中.为什么?

Nol*_*lty 11

问题是(很可能)你的制表符只是一堆空格.

>>> re.sub(r"\s+", " ", text)
"Hello my friends. How are you doing? I'm fine."
Run Code Online (Sandbox Code Playgroud)

  • 打败了我:) +1 (2认同)