Python: lstrip() vs removeprefix() and rstrip() vs removesuffix()

This is a confusion many people make.

It is easy to look at lstrip() and removeprefix() and wonder what is the real difference between the two.

When using lstrip(), the argument is a set of leading characters that will be removed as many times as they occur:

>>> word = 'hubbubbubboo'
>>> word.lstrip('hub')
'oo'

While removeprefix() will remove only the exact match:

>>> word = 'hubbubbubboo'
>>> word.removeprefix('hub')
'bubbubboo'

You can use the same rationale to distinguish between rstrip() and removesuffix().

>>> word = 'peekeeneenee'
>>> word.rstrip('nee')
'peek'
>>> word = 'peekeeneenee'
>>> word.removesuffix('nee')
'peekeenee'

And as a bonus, just in case you have never worked with regular expressions before, be grateful that you have strip() to trim character sets from a string instead of a regular expression:

>>> import re
>>> word = 'amazonia'
>>> word.strip('ami')
'zon'
>>> re.search('^[ami]*(.*?)[ami]*$', word).group(1)
'zon'

Watch on Youtube

You can also watch this content on Youtube: