Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

str.lstrip() unexpected behaviour

Tags:

python

I am working on a scrapy project and was trying to parse my config

The string is attr_title I have to strip 'attr_' and get title. I used lstrip('attr_'), but getting unexpected results. I know lstrip works out combinations and removes them, but having hard time understanding it.

In [17]: "attr.title".lstrip('attr.')
Out[17]: 'itle'

PS: I know there are multiple solutions for extracting string I am interested in understanding this.

like image 524
geetha ar Avatar asked Dec 08 '22 02:12

geetha ar


1 Answers

lstrip iterates over the result string until there is no more combination that matches the left most set of characters

A little illustration is below.

In [1]: "attr.title".lstrip('attr.')
Out[1]: 'itle'  # Flow --> "attr." --> "t" --> Next char is 'i' which does not match any combination hence, iteration stops & end result ('itle') is returned

In [2]: "attr.tritle".lstrip('attr.')
Out[2]: 'itle' # "attr." --> "t" --> "r" --> Next char is 'i' which does not match any combination hence, iteration stops & end result ('itle') is returned

In [5]: "attr.itratitle".lstrip('attr.')
Out[5]: 'itratitle' # "attr." --> Next char is 'i' which does not match any combination hence, iteration stops & end result ('itratitle') is returned
like image 172
kumar Avatar answered Dec 10 '22 16:12

kumar