2
votes

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'
>> a.lstrip('this')
out: 'at'
>> a.rstrip('cat')
out: 'thisth'

How does stripping a word works?

Ideally output should be "thist"(for first case) and 'that'(for second case) right?

Or is it like regular expression, matching each character, and whichever char it sees at the end it strips off (for third case)?

Note: I'm not looking for replace I just want to know how strip works while stripping a substring from the string.

3
for learning about strip with some example usecases, I suggest have a look at following link dotnetperls.com/strip-python - Manohar Swamynathan

3 Answers

8
votes

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.

1
votes
a = 'thisthat'    
a.rstrip('hat')

is equal to

a = 'thisthat' 
to_strip = 'hat'
while a[-1] in to_strip:
    a = a[:-2]
0
votes

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'