0

I am trying to match specific router interfaces. However, I am finding the below confusing, when searching for specific interface numbers, it is matching on the first condition, when i think it should be matching on the second condition:

string = ["TenGigE0/0/0/0.12", "TenGigE0/0/0/1.46", "TenGigE0/0/0/15.55"]

for item in string:
    if 'TenGigE0/0/0/0' in item or 'TenGigE0/0/0/1' in item:
        print("Yes")
    elif 'TenGigE0/0/0/15' in item:
        print("cool")

Output is:

Yes
Yes
Yes

How can i fix this?

2
  • 1
    Reverse the order of if/elif conditions. Commented May 5, 2021 at 16:00
  • This is because "'TenGigE0/0/0/15.55" and "'TenGigE0/0/0/1.46" starts with "'TenGigE0/0/0/1". Commented May 5, 2021 at 16:02

3 Answers 3

1

Change the if-statements around:

string = ["TenGigE0/0/0/0.12", "TenGigE0/0/0/1.46", "TenGigE0/0/0/15.55"]

for item in string:
    if 'TenGigE0/0/0/15' in item:
        print("cool")
    elif ('TenGigE0/0/0/0' in item) or ('TenGigE0/0/0/1' in item):
        print("Yes")

Will get you:

Yes
Yes
cool

Since TenGigE0/0/0/15 contains TenGigE0/0/0/1 too, and if you check for TenGigE0/0/0/1 before checking for TenGigE0/0/0/15 the first if-statement results in True

Sign up to request clarification or add additional context in comments.

Comments

1

Let's visualise this:

  • 'TenGigE0/0/0/0' in 'TenGigE0/0/0/0.12' is true, because 'TenGigE0/0/0/0' is a substring of 'TenGigE0/0/0/0.12':

    TenGigE0/0/0/0.12
    TenGigE0/0/0/0
    
  • 'TenGigE0/0/0/1' in 'TenGigE0/0/0/1.46' is true, because 'TenGigE0/0/0/1' is a substring of 'TenGigE0/0/0/1.46':

    TenGigE0/0/0/1.46
    TenGigE0/0/0/1
    
  • Same for 'TenGigE0/0/0/15.55':

    TenGigE0/0/0/15.55
    TenGigE0/0/0/1
    

if statement executes the code after the first condition that is True, so even though 'TenGigE0/0/0/15' in 'TenGigE0/0/0/15.55' is True, 'TenGigE0/0/0/1' in 'TenGigE0/0/0/15.55' was first, so that's what got executed.

Comments

1

As already mentioned in other answers, '/1' is a substring of '/15'.

Another solution is to use regex with a word bound \b and a group for '0' OR '1':

import re

string = ["TenGigE0/0/0/0.12", "TenGigE0/0/0/1.46", "TenGigE0/0/0/15.55"]
for item in string:
    if re.match(r'TenGigE0/0/0/(0|1)\b', item):
        print("Yes")
    elif re.match(r'TenGigE0/0/0/15\b', item):
        print("cool")

Output:

Yes
Yes
cool

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.