是否有一个Python函数将从字符串中删除空白(空格和制表符)?

所以给定的输入" \t example string\t "变成了"example string"


当前回答

#how to trim a multi line string or a file

s=""" line one
\tline two\t
line three """

#line1 starts with a space, #2 starts and ends with a tab, #3 ends with a space.

s1=s.splitlines()
print s1
[' line one', '\tline two\t', 'line three ']

print [i.strip() for i in s1]
['line one', 'line two', 'line three']




#more details:

#we could also have used a forloop from the begining:
for line in s.splitlines():
    line=line.strip()
    process(line)

#we could also be reading a file line by line.. e.g. my_file=open(filename), or with open(filename) as myfile:
for line in my_file:
    line=line.strip()
    process(line)

#moot point: note splitlines() removed the newline characters, we can keep them by passing True:
#although split() will then remove them anyway..
s2=s.splitlines(True)
print s2
[' line one\n', '\tline two\t\n', 'line three ']

其他回答

如果使用Python 3:在打印语句中,以sep=""结束。这样就把所有的空格分开了。

例子:

txt="potatoes"
print("I love ",txt,"",sep="")

这将打印: 我喜欢土豆。

而不是: 我喜欢土豆。

在您的情况下,由于您将试图获得\t,执行sep="\t"

在Python中,trim方法被命名为strip:

str.strip()  # trim
str.lstrip()  # left trim
str.rstrip()  # right trim

你也可以使用非常简单的基本函数:str.replace(),用于空格和制表符:

>>> whitespaces = "   abcd ef gh ijkl       "
>>> tabs = "        abcde       fgh        ijkl"

>>> print whitespaces.replace(" ", "")
abcdefghijkl
>>> print tabs.replace(" ", "")
abcdefghijkl

简单易行。

前导空格和尾随空格:

s = '   foo    \t   '
print s.strip() # prints "foo"

否则,正则表达式工作:

import re
pat = re.compile(r'\s+')
s = '  \t  foo   \t   bar \t  '
print pat.sub('', s) # prints "foobar"
    something = "\t  please_     \t remove_  all_    \n\n\n\nwhitespaces\n\t  "

    something = "".join(something.split())

输出:

please_remove_all_whitespaces

将Le Droid的评论添加到答案中。 用空格隔开:

    something = "\t  please     \t remove  all   extra \n\n\n\nwhitespaces\n\t  "
    something = " ".join(something.split())

输出:

请删除所有额外的空格