Eeternal Eeternal - 3 months ago 20
Python Question

Match similar item in list

I have 2 lists of hostnames

foo=['some-router-1', 'some-switch-1', 'some-switch-2']

bar=['some-router-1-lo','some-switch-1','some-switch-2-mgmt','some-switch-3-mgmt']


I would expect output to be like...

out=['some-switch-3-mgmt']


I want to find entries in
bar
that are not in
foo
. However some names in
bar
have
"-mgmt"
or some other string appended that don't occur in
foo
. The length and number of dashes per list item vary greatly, so I'm not sure how successful using a regex would be. I'm new to programming, so please provide some explanation if possible.

Answer

You can use startswith() to see if a string starts with another string. So something like:

out = [bar_string for bar_string in bar if not bar_string.startswith(tuple(foo))]