Determine prefix from a set of (similar) strings

前端 未结 9 2144
我在风中等你
我在风中等你 2020-11-27 14:25

I have a set of strings, e.g.

my_prefix_what_ever
my_prefix_what_so_ever
my_prefix_doesnt_matter

I simply want to find the longest common p

9条回答
  •  感动是毒
    2020-11-27 15:14

    Never rewrite what is provided to you: os.path.commonprefix does exactly this:

    Return the longest path prefix (taken character-by-character) that is a prefix of all paths in list. If list is empty, return the empty string (''). Note that this may return invalid paths because it works a character at a time.

    For comparison to the other answers, here's the code:

    # Return the longest prefix of all list elements.
    def commonprefix(m):
        "Given a list of pathnames, returns the longest common leading component"
        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
    

提交回复
热议问题