我如何修剪空白?

Chr*_*ris 1035 python string whitespace trim strip

是否有一个Python函数可以从字符串中修剪空格(空格和制表符)?

示例:\t example string\texample string

Jam*_*son 1549

双方空白:

s = "  \t a string example\t  "
s = s.strip()
Run Code Online (Sandbox Code Playgroud)

右侧的空白:

s = s.rstrip()
Run Code Online (Sandbox Code Playgroud)

左侧的空白:

s = s.lstrip()
Run Code Online (Sandbox Code Playgroud)

正如thedz指出的那样,你可以提供一个参数来将任意字符剥离到这些函数中,如下所示:

s = s.strip(' \t\n\r')
Run Code Online (Sandbox Code Playgroud)

这将去除任何空间,\t,\n,或\r从左侧字符,右手侧,或该字符串的两侧.

上面的示例仅从字符串的左侧和右侧删除字符串.如果您还要从字符串中间删除字符,请尝试re.sub:

import re
print re.sub('[\s+]', '', s)
Run Code Online (Sandbox Code Playgroud)

那应该打印出来:

astringexample
Run Code Online (Sandbox Code Playgroud)

  • strip()接受一个arguemnt来告诉它要去旅行的地方.尝试:strip('\ t \n\r') (17认同)
  • 无需列出空白字符:http://docs.python.org/2/library/string.html#string.whitespace (4认同)
  • 这些例子的结果应该非常有用:) (3认同)
  • @ JorgeE.Cardona - 你有点不对的一件事--`\s`将包含制表符,而`replace("","")`则不会. (3认同)
  • 最后一个例子就像使用`str.replace("","")`一样.您不需要使用`re`,除非您有多个空格,那么您的示例不起作用.`[]`用于标记单个字符,如果你只使用`\ s`则不需要.使用`\ s +`或`[\ s] +`(不必要的)但是`[\ s +]`不能完成这项工作,特别是如果你想用一个替换多个空格就像转动`"这个例如"`进``这个例子"`. (2认同)

gcb*_*gcb 71

trim调用Python 方法strip:

str.strip() #trim
str.lstrip() #ltrim
str.rstrip() #rtrim
Run Code Online (Sandbox Code Playgroud)

  • 这很容易记住,因为s ** tri ** p看起来几乎像** tri ** m。 (4认同)

ars*_*ars 22

对于前导和尾随空格:

s = '   foo    \t   '
print s.strip() # prints "foo"
Run Code Online (Sandbox Code Playgroud)

否则,正则表达式起作用:

import re
pat = re.compile(r'\s+')
s = '  \t  foo   \t   bar \t  '
print pat.sub('', s) # prints "foobar"
Run Code Online (Sandbox Code Playgroud)


Luc*_*cas 18

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

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

>>> print whitespaces.replace(" ", "")
abcdefghijkl
>>> print tabs.replace(" ", "")
abcdefghijkl
Run Code Online (Sandbox Code Playgroud)

简单易行.

  • 但是,唉,这也去除了内部空间,而原始问题中的示例未触及内部空间。 (2认同)

rob*_*ing 12

#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 ']
Run Code Online (Sandbox Code Playgroud)