2012-05-22 25 views
38

我想在Linux上的Python 2.7中删除所有空格/制表符/换行符。带空格/制表符/换行符 - python

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

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

输出:

I want to Remove all white spaces, new lines 
and tabs 

这似乎是一个简单的事情,但我在这里失去了一些东西。我应该输入什么东西?

+2

没有它不应该。 –

+1

可能是有用的:http://stackoverflow.com/questions/8928557/python-splitting-string-by-all-space-characters – newtover

+1

这对我来说,从:[如何修剪空白(包括标签)?] [1] S = s.strip( '\吨\ n \ R') [1]:http://stackoverflow.com/questions/1185524/how-to-trim-whitespace-包括标签 – stamat

回答

25

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

>>> 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 ' 

您可以.strip()如果你想,然后删除尾随的空间。

73

使用str.split([sep[, maxsplit]])没有sepsep=None

docs

如果未指定sep是或None,不同的分割算法 应用:连续空白的运行被视为单个 分隔符,结果将在起始 处不包含空字符串,或者如果字符串具有前导或尾随空白,则结束。

演示:

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

返回列表上使用str.join得到这个输出:

>>> ' '.join(myString.split()) 
'I want to Remove all white spaces, new lines and tabs' 
10
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 
+1

这也删除';' – jan

1

这只会移除标签,换行符空间,没有别的。

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

OUTPUT:

IwaoRemoveallwhiespaces,ewliesadabs

美好的一天!

1

使用重新

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 

输出:

IwanttoRemoveallwhitespaces,newlinesandtabs

相关问题