zoukankan      html  css  js  c++  java
  • python strip() lstrip() rstrip() 使用方法

    Python中的strip用于去除字符串的首尾字符串,同理,lstrip用于去除最左边的字符,rstrip用于去除最右边的字符。

    这三个函数都可传入一个参数,指定要去除的首尾字符。

    需要注意的是,传入的是一个字符数组,编译器去除两端所有相应的字符,直到没有匹配的字符,比如:

    theString = 'saaaay yes no yaaaass' 
    print theString.strip('say') 

    theString依次被去除首尾在['s','a','y']数组内的字符,直到字符在不数组内。所以,输出的结果为: 
    yes no 
    比较简单吧,lstrip和rstrip原理是一样的。

    注意:当没有传入参数时,是默认去除首尾空格的。 

    theString = 'saaaay yes no yaaaass' 
    print theString.strip('say') 
    print theString.strip('say ') #say后面有空格 
    print theString.lstrip('say') 
    print theString.rstrip('say') 
    

    运行结果: 

    yes no 
    es no 
    yes no yaaaass 
    saaaay yes no

    函数原型

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

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

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

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

    >>> s="  hello world "
    >>> string.strip(s)
    'hello world'
    string.strip(s)剔除字符串s左右空格

    >>> string.lstrip(s)
    'hello world '
    >>> string.rstrip(s)
    '  hello world'
    string.lstrip(s)和string.rstrip(s)分别剔除字符串左、右边的空格

    注意

    1. 当rm为空时,默认删除空白符(包括' ', ' ',  ' ',  ' ')

    例如:

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

    例如 :

    函数原型

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

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

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

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

    注意

    1. 当rm为空时,默认删除空白符(包括' ', ' ',  ' ',  ' ')

    例如:

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

    例如 :

    >>>a='123abc'

    >>>a.strip('21')

    '3abc'                                  结果都是一样的

    >>>a.strip('12')

    '3abc'

  • 相关阅读:
    完爆!用边缘容器,竟能秒级实现团队七八人一周的工作量
    手把手教你使用 cert-manager 签发免费证书
    手把手教你使用 Nginx Ingress 实现金丝雀发布
    Codeforces 534B Covered Path 贪心
    Codeforces 534A Exam 水
    Topcoder open 2015 Round 1A 250 Similars 枚举 + 状压
    Topcoder SRM 654 DIV1 500 FoldingPaper2 递归 + 枚举
    Topcoder SRM655 DIV2 250 BichromeBoard 水
    2015 Google code jam Qualification Round B 枚举 + 贪心
    2015 Google code jam Qualification Round A 水
  • 原文地址:https://www.cnblogs.com/guigujun/p/6120952.html
Copyright © 2011-2022 走看看