Determine prefix from a set of (similar) strings

前端 未结 9 2142
我在风中等你
我在风中等你 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:01

    Just out of curiosity I figured out yet another way to do this:

    def common_prefix(strings):
    
        if len(strings) == 1:#rule out trivial case
            return strings[0]
    
        prefix = strings[0]
    
        for string in strings[1:]:
            while string[:len(prefix)] != prefix and prefix:
                prefix = prefix[:len(prefix)-1]
            if not prefix:
                break
    
        return prefix
    
    strings = ["my_prefix_what_ever","my_prefix_what_so_ever","my_prefix_doesnt_matter"]
    
    print common_prefix(strings)
    #Prints "my_prefix_"
    

    As Ned pointed out it's probably better to use os.path.commonprefix, which is a pretty elegant function.

提交回复
热议问题