是否有一个Python函数可以修剪字符串中的空白(空格和制表符)?
例如: t example string
→ example string
。
两侧留白。
s = " \t a string example\t "
s = s.strip()
右侧留白。
s = s.rstrip()
左边的空白。
s = s.lstrip()
正如thedz所指出的,你可以为这些函数中的任何一个提供一个参数来剥离任意的字符,比如这样。
s = s.strip(' \t\n\r')
这将从字符串的左边、右边或两边剥离任何空格、t
、n
或r
字符。
上面的例子只从字符串的左手和右手边删除字符串。如果你还想从字符串的中间删除字符,请尝试re.sub
。
import re
print re.sub('[\s+]', '', s)
这应该会打印出来。
astringexample
#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 ']