删除带有换行符的空格

时间:2015-08-17 22:54:39

标签: python regex string whitespace removing-whitespace

我有一个看起来像这样的字符串:

"\n My name is John\n and I like to go.\n blahblahblah.\n \n\n ".

注意 - 在这个字符串示例中,新行字符后面有5个空格,但是后面可以是任意数量的空格。

我想使用正则表达式用一个空格替换那些"\n "子串。我一直在尝试各种正则表达式的组合,似乎没有什么工作正常。

关于正则表达式,我发现theString = string.replace(theString, '/\r?\n|\r/g', ' ')但它也不起作用。

我正在使用python 2.7

2 个答案:

答案 0 :(得分:0)

它不使用正则表达式,但是你可以这样做:

>>> s = "\n      My name is John\n      and I like to go.\n      blahblahblah.\n         \n\n      "
>>> " ".join(s.split())
'My name is John and I like to go. blahblahblah.'

答案 1 :(得分:0)

如果要分隔换行符,后面跟一个空格的空格:

s="\n      My name is John\n      and I like to go.\n      blahblahblah.\n         \n\n      "
import  re

print(repr(re.sub(r"(\s+)",r" ",s)))
' My name is John and I like to go. blahblahblah. '

替换那些" \ n"只有一个空格的子串

如果您想保留换行符:

print(repr(re.sub(r"(?<=\n)(\s+)",r" ",s)))
'\n My name is John\n and I like to go.\n blahblahblah.\n '