使用.strip()和正则表达式删除\\ n加空格不起作用

时间:2014-08-04 16:16:40

标签: python regex newline strip

我一直试图在字符串中的单词之前和之后删除\ n加上空格,但由于某种原因它不起作用。

这就是我的尝试:

.strip(my_string)

re.sub('\n', '', my string)

我尝试使用.stripre以使其正常工作,但它只返回相同的字符串。

示例输入:

\\n                    The people who steal our cards already know all of this...\\n
          \\n                    , \\n                    I\'m sure every fraud minded person in America is taking notes.\\n
            \\n                  

预期输出为:

The people who steal our cards already know all of this..., I\'m sure every fraud minded person in America is taking notes.

1 个答案:

答案 0 :(得分:2)

你可能正在寻找这样的东西:

re.sub(r'\s+', r' ', x)

一个用法示例如下:

In [10]: x
Out[10]: 'hello \n world   \n blue'

In [11]: re.sub(r'\s+', r' ', x)
Out[11]: 'hello world blue'

如果您还想抓住字符序列r'\n',那么让我们抓住它们:

 re.sub(r'(\s|\\n)+', r' ', x)

输出:

In [14]: x
Out[14]: 'hello \\n world  \n  \\n blue'

In [15]: re.sub(r'(\s|\\n)+', r' ', x)
Out[15]: 'hello world blue'