Python: Determine prefix from a set of (similar) strings -
i have set of strings, e.g.
my_prefix_what_ever my_prefix_what_so_ever my_prefix_doesnt_matter
i want find longest common portion of these strings, here prefix. in above result should be
my_prefix_
the strings
my_prefix_what_ever my_prefix_what_so_ever my_doesnt_matter
should result in prefix
my_
is there relatively painless way in python determine prefix (without having iterate on each character manually)?
ps: i'm using python 2.6.3.
never rewrite provided you: os.path.commonprefix
this:
return longest path prefix (taken character-by-character) prefix of paths in list. if list empty, return empty string (
''
). note may return invalid paths because works character @ time.
for comparison other answers, here's code:
# return longest prefix of list elements. def commonprefix(m): "given list of pathnames, returns longest common leading component" if not m: return '' s1 = min(m) s2 = max(m) i, c in enumerate(s1): if c != s2[i]: return s1[:i] return s1
Comments
Post a Comment