Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get common prefix of strings in a list [duplicate]

I need to know how to identify prefixes in strings in a list. For example,

list = ['nomad', 'normal', 'nonstop', 'noob']

Its answer should be 'no' since every string in the list starts with 'no'

I was wondering if there is a method that iterates each letter in strings in the list at the same time and checks each letter is the same with each other.

like image 576
Nick Avatar asked Feb 02 '26 16:02

Nick


1 Answers

Use os.path.commonprefix it will do exactly what you want.

In [1]: list = ['nomad', 'normal', 'nonstop', 'noob']

In [2]: import os.path as p

In [3]: p.commonprefix(list)
Out[3]: 'no'

As an aside, naming a list "list" will make it impossible to access the list class, so I would recommend using a different variable name.

like image 64
RedKnite Avatar answered Feb 05 '26 06:02

RedKnite



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!