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]删除序列是只要边边(开头或结尾)上的字符在删除序列内,就删除掉。

 

posted on 2018-01-17 09:34  实用才是硬道理  阅读(2969)  评论(0编辑  收藏  举报

导航