需求:
需要过滤掉输入字符串的前导,后续空格或其它字符.这在处理用户输入的时候比较有用.
讨论:
和其它语言类似,Python也提供了lstrip
,rstrip和strip方法,类似Delphi和C#的trim方法.
用法:
>>> x = ‘ test ‘
>>> print ‘|’, x.lstrip( ), ‘|’, x.rstrip( ), ‘|’, x.strip( ), ‘|’
| test | test | test |
另外,这三个方法还可以接受一个参数,用于过滤指定的字符组成的串
,如:
>>> x = ‘xyxxyy testyx yyx’
>>> print ‘|’+x.strip(’xy’)+’|’
| testyx |
需要注意的是:testyx前面有一个空格,因为空格前的所有的x
,y都被过滤掉了,而test后面的yx没有被过滤掉,是因为执行到testyx后面那个空格的时候就完成了.如果我们只需要留下’test’,输入下面的语句即可:
>>> print x.strip(’xy ‘)
test
相关说明:
lstrip(…)
S.lstrip([chars]) -> string or unicode
Return a copy of the string S with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping
rstrip(…)
S.rstrip([chars]) -> string or unicode
Return a copy of the string S with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping
strip(…)
S.strip([chars]) -> string or unicode
Return a copy of the string S with leading and trailing
whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping