当前位置:  首页>> 技术小册>> Python合辑2-字符串常用方法

2、strip()

strip()方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。

  1. s = ' hello '.strip()
  2. print(s)
  3. # hello
  4. s = '###hello###'.strip()
  5. print(s)
  6. # ###hello###

在使用strip()方法时,默认去除空格或换行符,所以#号并没有去除。
可以给strip()方法添加指定字符,如下所示。

  1. s = '###hello###'.strip('#')
  2. print(s)
  3. # hello

此外当指定内容不在头尾处时,并不会被去除。

  1. s = ' \n \t hello\n'.strip('\n')
  2. print(s)
  3. #
  4. # hello
  5. s = '\n \t hello\n'.strip('\n')
  6. print(s)
  7. # hello

第一个\n前有个空格,所以只会去取尾部的换行符。
最后strip()方法的参数是剥离其值的所有组合,这个可以看下面这个案例。

  1. s = 'www.baidu.com'.strip('cmow.')
  2. print(s)
  3. # baidu

最外层的首字符和尾字符参数值将从字符串中剥离。字符从前端移除,直到到达一个不包含在字符集中的字符串字符为止。
在尾部也会发生类似的动作。