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

后端 未结 11 2135
傲寒
傲寒 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:10

    import re
    
    def make_multi_prefix_replacer(prefixes):
        if isinstance(prefixes,str):
            prefixes = prefixes.split()
        prefixes.sort(key = len, reverse=True)
        pat = r'\b(%s)' % "|".join(map(re.escape, prefixes))
        print 'regex patern :',repr(pat),'\n'
        def suber(x, reg = re.compile(pat)):
            return reg.sub('',x)
        return suber
    
    
    
    pfxs = "x ya foobar yaku foo a|b z."
    replacer = make_multi_prefix_replacer(pfxs)               
    
    names = "xenon yadda yeti yakute food foob foobarre foo a|b a b z.yx zebra".split()
    for name in names:
        print repr(name),'\n',repr(replacer(name)),'\n'
    
    ss = 'the yakute xenon is a|bcdf in the barfoobaratu foobarii'
    print '\n',repr(ss),'\n',repr(replacer(ss)),'\n'
    

提交回复
热议问题