[Python-ideas] New explicit methods to trim strings

Steven D'Aprano steve at pearwood.info
Tue Apr 2 22:44:11 EDT 2019

On Tue, Apr 02, 2019 at 07:28:01PM +0100, MRAB wrote:
> >     word[len(prefix) if word.startswith(prefix) else 0:]
> >
> It could be 'improved' more to:
>     word[word.startswith(prefix) and len(prefix) : ]
> _Neither_ version copies if the word doesn't start with the prefix. If 
> you won't believe me, test them! :-)

That slicing doesn't make a copy of the string is an implementation- 
dependent optimization, not a language guarantee. It's an obvious 
optimization to make (and in my testing, it does work all the way back 
to CPython 1.5) but if you want to write implementation-independent 
code, you shouldn't rely on it.

By the letter of the language spec, an interpreter may make a copy of a 
string when doing a full slice string[0:len(string)].


More information about the Python-ideas mailing list