Chinaunix首页 | 论坛 | 博客
  • 博客访问: 126501
  • 博文数量: 83
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 585
  • 用 户 组: 普通用户
  • 注册时间: 2014-05-13 10:26
个人简介

- 毅力与勇气是事业的双飞翼; - 在尝试中成长,在失败中奋起。 - 概览 -> 细读 -> 概览 - 书不在多,在于精。

文章分类

全部博文(83)

文章存档

2016年(2)

2015年(6)

2014年(75)

我的朋友

分类: LINUX

2014-05-23 15:32:22

Python中的strip用于去除字符串的首尾字符串(从左往右 从右往左匹配参数中的字符串,直到碰到不在参数中的字符结束,同理,lstrip用于去除最左边的字符(从左往右匹配参数中的字符串,直到碰到不在参数中的字符结束,rstrip用于去除最右边的字符(从右往左匹配参数中的字符串,直到碰到不在参数中的字符结束

这三个函数都可传入一个参数,指定要去除的首尾字符。

需要注意的是,传入的是一个字符数组,编译器去除两端所有相应的字符,直到没有匹配的字符,比如:
theString = 'saaaay yes no yaaaass'
print theString.strip('say')

theString依次被去除首尾在['s','a','y']数组内的字符,直到字符在不数组内。所以,输出的结果为: 
yes no 

若:theString = 'sattaaay yes no yaaaass'
则,print theString.strip('say')结果为 'ttaaay yes no '

若:theString = 'tttsattaaay yes no ttyaaattass'
,print theString.strip('say')结果为 'tttsattaaay yes no ttyaaatt'

若:theString = 'tttsattaaay yes no ttyaaattassttt'
,print theString.strip('say')结果为 'tttsattaaay yes no ttyaaattassttt'


比较简单吧,lstrip和rstrip原理是一样的。

注意:当没有传入参数时,是默认去除首尾空格的。 
theString = 'saaaay yes no yaaaass'
print theString.strip('say')
print theString.strip('say ') #say后面有空格
print theString.lstrip('say')
print theString.rstrip('say')

运行结果: 

yes no #前后有空格即 ' yes no '
es no  #前后无空格即 'es no'
yes no yaaaass  #前面有空格即' yes no yaaaass'
saaaay yes no    #后面有空格即'saaaay yes no '

转自:http://www.cnblogs.com/pylemon/archive/2011/05/18/2050179.html

阅读(420) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~