rstrip,strip,lstrip

作用:去除字符串中的空格或指定字符

一、默认用法:去除空格
str.strip()  : 去除字符串两边的空格
str.lstrip() : 去除字符串左边的空格
str.rstrip() : 去除字符串右边的空格

注:此处的空格包含'\n', '\r',  '\t',  ' '

例如:

  >>>str ='  Hello World \t\r\n'

  >>>print str.strip()

  >>>'Hello World'

 

  >>>print str.lstrip()

  >>>'Hello World \t\r\n'

 

  >>>print str.rstrip()

  >>>'  Hello World'

二、去除指定字符

  str.strip('ab')  :去除字符串两端指定的字符
  str.lstrip('ab') :用于去除左边指定的字符
  str.rstrip('ab') :用于去除右边指定的字符

  三个函数都可以传入一个参数(这里以'ab'为例),指定要去除的首尾字符,编译器会去除两端所有相应的字符,直到没有匹配的字符

  注:
  1.去除指定字符时首尾不能出现空格,否则传入参数的时候也需要加入空格
  2.指定的字符表示的一种组合,例如'ab'表示'aa','ab','ba','bb','aaa','bbb'等

  例如:

  >>>str = "say hello say boy saaayaaas"

  >>>print str.strip()

  >>>hello say boy 

 

相关文章:

  • 2021-07-13
  • 2022-12-23
  • 2021-06-08
  • 2021-09-15
  • 2022-12-23
  • 2021-12-12
  • 2021-12-13
  • 2021-05-25
猜你喜欢
  • 2021-10-10
  • 2021-10-01
  • 2022-12-23
  • 2022-12-23
  • 2021-08-20
  • 2021-07-25
相关资源
相似解决方案