pythonprefixsuffix

Get the suffix from a list of similar string


# code to get commonprefix
    def commonprefix(m):
        if not m: return ''
        s1 = min(m)
        s2 = max(m)
        for i, c in enumerate(s1):
            if c != s2[i]:
                return s1[:i]
        return s1
#code to get the different suffix 
    strList = map(str, objList)
    strList = map(lambda x: x.replace('', ''), strList)  

# My code to get the different suffix of each element of a list 

    for i in range(len(liste)):

        Listelement = liste[i]["title"].tolist()
        common_name = commonprefix(Listelement)
        try:
            strList = map(str, Listelement) 
            strList = map(lambda x: x.replace(common_name, ''), strList)
            print(Listelement)
        except:
            pass

# this is how my "Listelement" variable look like

    ['Le Coton Coton Extra Doux Boîte 100pce - CHANEL']
    ['Allure Eau De Toilette Vaporisateur 50ml - CHANEL', 'Allure Eau De Toilette Vaporisateur 100ml - CHANEL']
    ['Allure Eau De Toilette Vaporisateur 50ml - CHANEL', 'Allure Eau De Toilette Vaporisateur 100ml - CHANEL']
    ['Eau De Cologne Les Exclusifs De Chanel 75ml - CHANEL', 'Eau De Cologne Les Exclusifs De Chanel 200ml - CHANEL']
    ['Eau De Cologne Les Exclusifs De Chanel 75ml - CHANEL', 'Eau De Cologne Les Exclusifs De Chanel 200ml - CHANEL']

Hi guys I have a small problem to find the suffix of my list of products. I got the common prefix function which give me for my list the correct answer but when i try to remove the common_prefix for each element of each list, it doesn't work, do you have any idea why? thank you so much


Solution

    1. You need not reinvent the wheel for os.path.commonprefix.
    2. In addition, you can use slicing syntax on string instead of counting characters one-by-one.

    Solution

    import re
    import os
    
    ls = ['Allure Eau De Toilette Vaporisateur 50ml - CHANEL', 'Allure Eau De Toilette Vaporisateur 100ml - CHANEL']
    
    # find common prefix
    pfx = os.path.commonprefix(ls)
    ans = [el[len(pfx):] for el in ls]
    print(ans)  # ['50ml - CHANEL', '100ml - CHANEL']