使用.strip()和regex剥离\\n加上空格不起作用

2024-10-04 05:23:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直试图从字符串中删除\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.

Tags: ofthe字符串restringmyourall
1条回答
网友
1楼 · 发布于 2024-10-04 05:23:35

你可能在找这样的东西:

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'

相关问题 更多 >