我有一组字符串,例如 my_prefix_what_evermy_prefix_what_so_evermy_prefix_doesnt_matter 我只是想找到这些字符串中最长的公共部分,这里是前缀.在上面的结果应该是 my_prefix_ 字符串 my_prefix_what_evermy_p
my_prefix_what_ever my_prefix_what_so_ever my_prefix_doesnt_matter
我只是想找到这些字符串中最长的公共部分,这里是前缀.在上面的结果应该是
my_prefix_
字符串
my_prefix_what_ever my_prefix_what_so_ever my_doesnt_matter
应该导致前缀
my_
在Python中有一种相对无痛的方法来确定前缀(无需手动迭代每个字符)吗?
PS:我使用的是Python 2.6.3.
永远不要改写提供给你的东西:os.path.commonprefix
就是这样:
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.
为了与其他答案进行比较,这里是代码:
# 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