带空格/制表符/换行符-python

2024-03-28 13:08:31 发布

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

我正在尝试删除Linux上Python2.7中的所有空格/制表符/换行符。

我写了这篇文章,它应该可以完成这项工作:

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

这似乎是一件简单的事情,但我在这里错过了一些东西。我应该进口点什么吗?


Tags: andtonewlinuxallremove制表符spaces
3条回答

如果要删除多个空白项并用单个空格替换它们,最简单的方法是使用这样的regexp:

>>> 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()删除尾随空格。

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

使用str.split([sep[, maxsplit]])而不使用sepsep=None

来自docs

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

演示:

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

相关问题 更多 >