[Python-ideas] New explicit methods to trim strings

Stephen J. Turnbull turnbull.stephen.fw at u.tsukuba.ac.jp
Tue Apr 2 14:10:07 EDT 2019

Anders Hovmöller writes:

 > Removing "file:" prefix:
 > https://github.com/merijn/dotfiles/blob/43c736c73c5eda413dc7b4615bb679bd43a18d1a/dotfiles/hg-data/hooks/bitbucket.py#L16 <https://github.com/merijn/dotfiles/blob/43c736c73c5eda413dc7b4615bb679bd43a18d1a/dotfiles/hg-data/hooks/bitbucket.py#L16>

This is interesting, because it shows the (so far standard) one-liner:

    word[len(prefix):] if word.startswith(prefix) else word

can be improved (?!) to

    word[len(prefix) if word.startswith(prefix) else 0:]

I don't know if this is more readable, but I think it's less so.

Note that version 1 doesn't copy word if it doesn't start with prefix,
while version 2 does.  In many applications I can think of the results
would be accumulated in a set, and version 1 equality tests will also
be faster in the frequent case that the word doesn't start with the
prefix.  So that's the one I'd go with, as I can't think of any
applications where multiple copies of the same string would be useful.


More information about the Python-ideas mailing list