strip() ----python字符串去除【首尾】空白或包含特定字符

一听到去空白

直觉反应就是strip()

结果怎么老得不到我要的结果呢? 

就是这么一段句子,

"I just read this in a newspaper"

想试一下算算包含了几个英文字母,

怎么都去不掉空白啊......

>>> s=s="I just read this in a newspaper"
>>> s.strip()
'I just read this in a newspaper'

再仔细看一下定义

S.strip([chars]) -> str

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.

==>人家都告诉你移除的是自首和字尾的空白了,当然就只移除头尾处空白了

除了移除空白,他还可以移除别的,不过还是一样,只限于移除两边,跟边没关系的不移
看一下例子
>>> s=s="I just read this in a newspaper"
>>> s.strip('re')

'I just read this in a newspap'

>>> s.strip('er')

'I just read this in a newspap'

>>> s.strip('epr')

'I just read this in a newspa'

发现了没,()内的字,不一定要顺序一样,只要个数一样且包含的字符也一样就去掉,不管是re还是er

 

注意:

(1)当[chars]为空时,就是删除边边的空白符啦(包括'\n', '\r', '\t',  ' ')

(2)这里的[chars]删除序列是只要边边(开头或结尾)上的字符在删除序列内,就删除掉。

 

转载于:https://www.cnblogs.com/mikeblog/p/8299308.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值