首页 > 技术文章 > Python strip()方法

xysr-tom 2019-04-25 10:48 原文

描述

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

注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。

语法

strip()方法语法:

str.strip([chars]);

参数

  • chars -- 移除字符串头尾指定的字符序列。

返回值

返回移除字符串头尾指定的字符生成的新字符串。

实例

以下实例展示了strip()函数的使用方法:

实例(Python 2.0+)
#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
str = "00000003210Runoob01230000000"; 
print str.strip( '0' );  # 去除首尾字符 0
 
 
str2 = "   Runoob      ";   # 去除首尾空格
print str2.strip(); 

以上实例输出结果如下:

3210Runoob0123
Runoob

从结果上看,可以注意到中间部分的字符并未删除。

以上下例演示了只要头尾包含有指定字符序列中的字符就删除:

实例

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
str = "123abcrunoob321"
print (str.strip( '12' ))  # 字符序列为 12

以上实例输出结果如下:

3abcrunoob3

  

3 篇笔记 写笔记

  • 只移除字符串头尾指定的字符,中间部分不会移除:
#!/usr/bin/python

str = "0000000this is string 0000example....wow!!!0000000";
print str.strip( '0' );

输出结果中间部分的 0 还是存在的:

this is string 0000example....wow!!!
  • 像 lstrip 和 rstrip 一样,strip() 也可以带多个字符参数,测试如下:
# -*- coding:utf-8 -*-

str1 = '    iam string  '

print "str1:\'%s\'" %str1
print "str1.strip():\'%s\'" %str1.strip()

str2 = '@@@@@iamstring@@@@@'
print "str2:\'%s\'" %str2
print "str2.strip('@'):\'%s\'" %str2.strip('@')
print "str2.strip('@@'):\'%s\'" %str2.strip('@@')
print "str2.strip('@@@@@@'):\'%s\'" %str2.strip('@@@@@@')
print "str2.strip('@i'):\'%s\'" %str2.strip('@i')
print "str2.strip('@ag'):\'%s\'" %str2.strip('@g')

输出结果为:

str1:'  iam string  '
str1.strip():'iam string'
str2:'@@@@@iamstring@@@@@'
str2.strip('@'):'iamstring'
str2.strip('@@'):'iamstring'
str2.strip('@@@@@@'):'iamstring'
str2.strip('@i'):'amstring'
str2.strip('@ag'):'iamstrin'
  • 从第二个序列看出来好像并不是指定序列:
str = "123abcrunoob321"
print (str.strip( '12' )) # 字符序列为 12 ?

因为输出:

3abcrunoob3

结尾的难不成是从右向左寻找??

带着疑问我测试了几次,发现:

str = "123abcrunoob3221"print (str.strip( '32b1' ))

输出:

abcrunoo

看起来像是参数中每个字符 3 2 b 1 都是独立的,

在开头从左向右依次查找字符,如果是这几个中的一个就删除,继续往下找,若不是,就终止,所以开头保留到a 。

在结尾从右往左查找,同上,而且结尾的 22 可以重复删除。如果有不正确的地方期待指正。

推荐阅读