问题:
需要过滤掉输入字符串的前导,后续空格或其它字符.这在处理用户输入的时候比较有用.
解决方法:
lstrip, rstrip, 和 strip 方法,没有参数:
>>> x = ' hej '
>>> print '|', x.lstrip( ), '|', x.rstrip( ), '|', x.strip( ), '|'
| hej | hej | hej |
另外,这三个方法还可以接受一个参数,用于过滤指定的字符组成的串 ,如:
>>> x = 'xyxxyy hejyx yyx'
>>> print '|'+x.strip('xy')+'|'
| hejyx |
需要注意的是:hejyx前面有一个空格,因为空格前的所有的x,y都被过滤掉了,而hej后面的yx没有被过滤掉,是因为执行到hejyx后面那个空格的时候就完成了.如果我们只需要留下'hej',输入下面的语句即可:
>>> print x.strip('xy ')
hej
相关说明:
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