strip函数

一、strip函数原型

声明:s为字符串,rm为要删除的字符序列

s.strip(rm)        删除s字符串中开头、结尾处,位于rm删除序列的字符

s.lstrip(rm)       删除s字符串中开头处,位于 rm删除序列的字符

s.rstrip(rm)      删除s字符串中结尾处,位于 rm删除序列的字符

如下

1
2
3
4
5
6
7
8
>>> a= 'hheloooo goooodbyyyye'
>>> a.strip( 'helo ' )
'goooodbyyyy'
>>> a.strip( 'he' )
'loooo goooodbyyyy'
>>> a.strip( 'o' )
'hheloooo goooodbyyyye'
>>>

从首尾开始找.先从首位找到'h'['h','e','l','o']内把'h'去掉,发现第二个'h'依然还在['h','e','l','o']内再次去掉'h',往后推,发现'e'还在['h','e','l','o'],继续去掉'e',同理一直往下推.

从尾部开始发现'e'['h','e','l','o'],去掉'e',再发现'y'不在['h','e','l','o'],所以就停止了.

 

 

1, rm为空时,默认删除空白符(包括'\n', '\r',  '\t',  ' ')

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
>>> a= '    a\n\tbc'
>>> print a
     a
        bc
>>> a.strip()
'a\n\tbc'
>>> a= '  abc'
>>> a.strip()
'abc'
>>> a= '\n\tabc'
>>> a.strip()
'abc'
>>> a= 'abc\n\t'
>>> a.strip()
'abc'
>>>

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
>>> a= '123abc'
>>> a.strip( '21' )
'3abc'
>>> a.strip( '12' )
'3abc'
>>> a.strip( '1a' )
'23abc'
>>> a.strip(cb)
Traceback (most recent call last):
  File  "<stdin>" , line 1,  in  <module>
NameError: name  'cb'  is not defined
>>> a.strip( 'cb' )
'123a'
>>> a.strip( 'bc' )
'123a'
>>>

二、split函数

split是分割函数,将字符串分割成“字符”,保存在一个列表中。

1
2
3
>>> a= 'a b c d'
>>> a. split ()
[ 'a' 'b' 'c' 'd' ]

默认不带参数为空格分割。之所以为双引号的“字符”,因为实际python没有字符的。

1
2
3
>>> b= 'abc efg hij kkj'
>>> b. split ()
[ 'abc' 'efg' 'hij' 'kkj' ]

还可以带参数根据实际需求进行分割

1
2
3
4
5
>>> c= 'name=ding|age=25|job=it'
>>> c. split ( '|' )
[ 'name=ding' 'age=25' 'job=it' ]
>>> c. split ( '|' )[0]. split ( '=' )
[ 'name' 'ding' ]

还可以带上数字参数,表示“切几刀”如:

 

1
2
3
4
5
6
7
8
9
10
11
>>> d= 'a b c d e'
>>> d. split ( ' ' ,1) #以空格“切一刀”,就分成两块了
[ 'a' 'b c d e' ]
>>> d. split ( ' ' ,2)
[ 'a' 'b' 'c d e' ]
>>> d. split ( ' ' ,3)
[ 'a' 'b' 'c' 'd e' ]
>>> d. split ( ' ' ,-1)  #d.split(' ')结果一样
[ 'a' 'b' 'c' 'd' 'e' ]
>>> d. split ( ' ' )
[ 'a' 'b' 'c' 'd' 'e' ]

 


本文出自 “丁同学1990” 博客,请务必保留此出处http://dingtongxue1990.blog.51cto.com/4959501/1675499

posted @ 2022-08-19 23:00  luoganttcc  阅读(97)  评论(0编辑  收藏  举报