[Tutor] str.strip strange result...?

Albert-Jan Roskam sjeik_appie at hotmail.com
Sun Jan 17 17:14:53 EST 2016


> To: tutor at python.org
> From: __peter__ at 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'


 		 	   		  


More information about the Tutor mailing list