Python3 strip()方法

前言

我们在处理字符串的时候,总会遇到这种问题,一个字符串,中间是我们想要的内容,两边会多出来一些内容确定、数量不定字符,比如这样:

str_sample = "-* This is a sample!\n###"

我希望去掉这个字符串两头的“-”、“*”、“\n”、“#”以及“ ”,只想保留"This is a sample!"应该怎么处理呢?

语法

str.strip([chars])
官方解释:

Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:

  • 返回字符串的一个副本,去掉前面和后面的字符。chars参数是一个字符串,指定要删除的字符集。如果省略或没有,chars参数默认为删除空格。chars参数不是前缀或后缀;相反,它的值的所有组合都被剥离。

参数与示例

  1. 参数可以为空,表示去掉头尾的空格。
>>> '   spacious   '.strip()
'spacious'
  1. 当我们想去除的字符出现了多次,参数中只需要输入一次我们想去除的字符即可。
>>> "###crystal".strip("#")
'crystal'
>>> 

3.当头尾想去除的内容不同时,只需要分别把我们希望去除的字符一次添加到参数中即可。

>>> 'www.example.com'.strip('cmowz.')
'example'
  • 参数为“cmowz.”。我们发现,这个'www.example.com'字符串,头的"w"".",尾的"c""o""m""."都被去除了,且我们输入参数时,不需要按照顺序输入。

最后

前言中的str_sample = "-* This is a sample!\n###",我们希望提取"This is a sample!",应该怎么操作呢?

>>> "-* This is a sample!\n###".strip("-* \n#")
'This is a sample!'

你可能感兴趣的:(Python3 strip()方法)