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)
gcb*_*gcb 71
trim调用Python 方法strip:
str.strip() #trim
str.lstrip() #ltrim
str.rstrip() #rtrim
Run Code Online (Sandbox Code Playgroud)
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)
简单易行.
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)