【问题标题】:Stripping out \\n plus whitespace using .strip() and regex is not working使用 .strip() 和正则表达式去除 \\n 加空格并不起作用
【发布时间】:2014-08-04 16:16:40
【问题描述】:

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

这是我尝试过的:

.strip(my_string)

和

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

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

示例输入:

\\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.

【问题讨论】:

  • 您需要出示您的代码
  • 您是要删除一个实际的换行符\n,还是删除\ 字符后跟n 字符?
  • 请附上您自己的尝试,并告诉我们如何它不起作用。包括您收到的任何错误消息。
  • 我其实不知道里面有人物
  • 并添加预期的输出。

标签: python regex newline strip


【解决方案1】:

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

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'

【讨论】:

  • 这几乎可以工作,因为它删除了空白,但 \\n 仍然存在。
  • \\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)组成的字符串,而 '\n' 是一个单个字符(一个换行符)。话虽如此,我已经编辑了我的答案。
猜你喜欢
  • 1970-01-01
  • 2013-03-08
  • 1970-01-01
  • 2020-09-03
  • 1970-01-01
  • 2021-04-10
  • 2019-05-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多