python-从一组(相似)字符串中确定前缀
我有一组字符串,例如
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。
Kawu asked 2019-10-06T18:57:22Z
8个解决方案
112 votes
永远不要重写提供给您的内容:''正是这样做的:
返回最长路径前缀(采用 个字符),它是列表中所有路径的前缀。 如果清单 为空,则返回空字符串('')。 请注意,这可能会返回 无效的路径,因为它一次可以处理一个字符。
为了与其他答案进行比较,下面是代码:
# 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 ''