Pradeep Pillai Pradeep Pillai - 3 months ago 12
Python Question

Function string.lstrip() returns blank string in python

In the python interpreter:
'pradeep'.lstrip('prade') gives an output of ''.
I was expecting this to return 'ep'.
Why is that assumption wrong ?

Answer

.lstrip() removes the set of characters, not a word. All characters p, r, a, d and e, in any order, are removed from the start of pradeep. The last two characters e and d are still part of that set and are removed as well. You would get the same result if you used .lstrip('drape') or .lstrip('adepr').

If you want to remove a word from the start, use slicing:

example = 'pradeep'
example[5:] if example.startswith('prade') else example

or, as a function:

def remove_start(inputstring, word_to_remove):
    return inputstring[len(word_to_remove):] if inputstring.startswith(word_to_remove) else inputstring

Demo:

>>> def remove_start(inputstring, word_to_remove):
...     return inputstring[len(word_to_remove):] if inputstring.startswith(word_to_remove) else inputstring
... 
>>> remove_start('pradeep', 'prade')
'ep'
Comments