> To: tutor@python.org > From: __pete...@web.de > Date: Fri, 15 Jan 2016 17:37:25 +0100 > Subject: Re: [Tutor] str.strip strange result...? > > Jignesh Sutar wrote: > > > #python2.7 > > > >>>> s="V01_1" > >>>> s.strip("_1") > > 'V0' > > > > > > Wouldn't you expect the result to be "V01" ? > > str.strip() doesn't strip off a suffix or prefix; its first argument is > interpreted as a character set, i. e. as long as s ends/starts with any of > the characters "_" or "1", remove that. > > If you want to remove a suffix you have to write > > if suffix and s.endswith(suffix): > s = s[:-len(suffix)]
Not sure which one is faster, but in this case I actually find a regex more readable (!): >>> re.sub(r"_1$", "", "V01_1") 'V01' Without the $ sign may also do the trick, but: >>> re.sub(r"_1", "", "V01_1_1") 'V01' >>> re.sub(r"_1$", "", "V01_1_1") 'V01_1' _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor