How does strip works in python?

后端 未结 3 627
星月不相逢
星月不相逢 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'
    

提交回复
热议问题