Python Cookbook学习记录 ch1_5_2013/10/22

1.5去除字符串两端的空格

这一节的内容相当于上一节字符串对齐的逆操作。

可以使用string对象的lstrip,rstrip和strip方法来完成相应的操作,分别用于删除开头,末尾和两端的空格。

>>> x = '     hello     '
>>> print x.lstrip()+'|'
hello     |
>>> print x.rstrip()+'|'
     hello|
>>> print x.strip()+'|'
hello|

其中这几个方法都是可以带参数的,带上参数后上述方法将从左右一直寻找首尾都在参数字符内的字符串,然后将其删去(=_=||| 感觉这么写没有其他人看得懂,看来表达能力不行呀)

>>> x = 'ab axy  abbaba'
>>> print '|'+x.strip('ab')+'|'
| axy  |
>>> print '|'+x.strip('ab ')+'|' #参数加了个空格!
|xy|

 

 

posted on 2013-10-22 22:36  七海之风  阅读(115)  评论(0)    收藏  举报

导航