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
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'
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.
a = 'thisthat'
a.rstrip('hat')
is equal to
a = 'thisthat'
to_strip = 'hat'
while a[-1] in to_strip:
a = a[:-2]