How does strip works in python?

后端 未结 3 628
星月不相逢
星月不相逢 2020-12-21 15:35

I want to know how does rstrip and lstrip works in python. Say, if I have a string

>> a = \'thisthat\'
>> a.rstrip(\'hat\')
out : \'this\'
>&g         


        
相关标签:
3条回答
  • 2020-12-21 15:54

    lstrip, rstrip and strip remove characters from the left, right and both ends of a string respectively. By default they remove whitespace characters (space, tabs, linebreaks, etc)

    >>> a = '  string with spaces  '
    >>> a.strip()
    'string with spaces'
    >>> a.lstrip()
    'string with spaces  '
    >>> a.rstrip()
    '  string with spaces'
    

    You can use the chars parameter to change the characters it strips.

    >>> a = '....string....'
    >>> a.strip('.')
    'string'
    

    However, based on your question it sounds like you are actually looking for replace

    >>> a = 'thisthat'
    >>> a.replace('hat', '')
    'thist'
    >>> a.replace('this', '')
    'that'
    
    0 讨论(0)
  • 2020-12-21 16:04

    From the doc:

    Return a copy of the string with leading and trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the both ends of the string this method is called on.

    strip takes a charcters parameter and will try to remove those characters from both end as long as it can.

    The parameter is considered as a set of charcters, not as a substring.

    lstrip and rstrip works exactly same way, only difference is one of them strip only from left, and another from right side.

    0 讨论(0)
  • 2020-12-21 16:08
    a = 'thisthat'    
    a.rstrip('hat')
    

    is equal to

    a = 'thisthat' 
    to_strip = 'hat'
    while a[-1] in to_strip:
        a = a[:-2]
    
    0 讨论(0)
提交回复
热议问题