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

后端 未结 11 2073
傲寒
傲寒 2021-01-01 12:16

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         


        
11条回答
  •  生来不讨喜
    2021-01-01 13:00

    Could use a simple regex.

    import re
    prefixes = ("i_", "c_", "longer_")
    re.sub(r'^(%s)' % '|'.join(prefixes), '', name)
    

    Or if anything preceding an underscore is a valid prefix:

    name.split('_', 1)[-1]
    

    This removes any number of characters before the first underscore.

提交回复
热议问题