Search code examples
pythonstringvariable-lengthprefixes

Finding whether a string starts with one of a list's variable-length prefixes


I need to find out whether a name starts with any of a list's prefixes and then remove it, like:

if name[:2] in ["i_", "c_", "m_", "l_", "d_", "t_", "e_", "b_"]:
    name = name[2:]

The above only works for list prefixes with a length of two. I need the same functionality for variable-length prefixes.

How is it done efficiently (little code and good performance)?

A for loop iterating over each prefix and then checking name.startswith(prefix) to finally slice the name according to the length of the prefix works, but it's a lot of code, probably inefficient, and "non-Pythonic".

Does anybody have a nice solution?


Solution

  • A bit hard to read, but this works:

    name=name[len(filter(name.startswith,prefixes+[''])[0]):]