剥离空格/标签/换行符 - python

bac*_*m09 75 python string strip python-2.7

我试图在Linux上删除python 2.7中的所有空格/制表符/换行符.

我写了这个,应该做的工作:

myString="I want to Remove all white \t spaces, new lines \n and tabs \t"
myString = myString.strip(' \n\t')
print myString
Run Code Online (Sandbox Code Playgroud)

输出:

I want to Remove all white   spaces, new lines 
 and tabs
Run Code Online (Sandbox Code Playgroud)

这似乎是一件简单的事情,但我在这里缺少一些东西.我应该进口什么吗?

Ash*_*ary 107

使用str.split([sep[, maxsplit]])no sepsep=None:

来自docs:

如果sep未指定或是None,则应用不同的拆分算法:连续空格的运行被视为单个分隔符,如果字符串具有前导或尾随空格,则结果将在开头或结尾处不包含空字符串.

演示:

>>> myString.split()
['I', 'want', 'to', 'Remove', 'all', 'white', 'spaces,', 'new', 'lines', 'and', 'tabs']
Run Code Online (Sandbox Code Playgroud)

使用str.join返回的名单上得到这个输出:

>>> ' '.join(myString.split())
'I want to Remove all white spaces, new lines and tabs'
Run Code Online (Sandbox Code Playgroud)


Mat*_*ttH 46

如果你想删除多个空白项并用单个空格替换它们,最简单的方法是使用这样的正则表达式:

>>> import re
>>> myString="I want to Remove all white \t spaces, new lines \n and tabs \t"
>>> re.sub('\s+',' ',myString)
'I want to Remove all white spaces, new lines and tabs '
Run Code Online (Sandbox Code Playgroud)

然后,您可以根据需要删除尾随空格.strip().


Man*_*ani 11

import re

mystr = "I want to Remove all white \t spaces, new lines \n and tabs \t"
print re.sub(r"\W", "", mystr)

Output : IwanttoRemoveallwhitespacesnewlinesandtabs
Run Code Online (Sandbox Code Playgroud)

  • 这也删除';' (3认同)

Shi*_*kar 8

使用re

import re
myString = "I want to Remove all white \t spaces, new lines \n and tabs \t"
myString = re.sub(r"[\n\t\s]*", "", myString)
print myString
Run Code Online (Sandbox Code Playgroud)

输出:

IwanttoRemoveallwhitespaces,newlinesandtabs

  • 这不会保留单词之间的空格,从而使文本对 NLP 毫无用处。 (2认同)

The*_*ron 7

这只会删除选项卡,换行符,空格以及其他所有内容。

import re
myString = "I want to Remove all white \t spaces, new lines \n and tabs \t"
output   = re.sub(r"[\n\t\s]*", "", myString)
Run Code Online (Sandbox Code Playgroud)

输出:

Iwanto删除所有空格,换行符和标签

美好的一天!


ros*_*ipi 7

上述建议使用正则表达式的解决方案并不理想,因为这是一个很小的任务,正则表达式需要的资源开销比任务的简单性所证明的要多。

这是我所做的:

myString = myString.replace(' ', '').replace('\t', '').replace('\n', '')

或者如果你有一堆东西要删除,以至于单行解决方案会很长:

removal_list = [' ', '\t', '\n']
for s in removal_list:
  myString = myString.replace(s, '')
Run Code Online (Sandbox Code Playgroud)