How to remove tabs and newlines with a regex

自古美人都是妖i 提交于 2021-02-16 05:08:22

问题


In Python 3.x, the special re sequence '\s' matches Unicode whitespace characters including [ \t\n\r\f\v].

The following piece of code is intended to replace tabs and newlines with a space.

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

However, the tab is still present in output. Why?


回答1:


The problem is(likely) that your tab character is just a bunch of spaces.

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


来源:https://stackoverflow.com/questions/16355732/how-to-remove-tabs-and-newlines-with-a-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!