I have a list of multiple items. Need to create a loop that finds an item from the list and prints it out. If item not found prints out only once that it hasn't been found.
for x in range(len(regs)):
rex = regs[x]
if re.match(rex,hostname):
print (dev[x],'Regex matched')
break
else:
print('wrong format')
Currently it prints out multiple times that it hasn't been found. When it matches the regex it prints out at the end. I only want the If Else to prints "wrong format" once.
currently prints out wrong format wrong format wrong format wrong format wrong format wrong format wrong format "DeviceX Regex matched"
-
a simple solution will be to use a flagAndy_101– Andy_1012019年09月13日 10:32:47 +00:00Commented Sep 13, 2019 at 10:32
5 Answers 5
Use else with for.
As you are breaking out of the for loop as soon as you find one item, the below code will work fine:
for x in range(len(regs)):
rex = regs[x]
if re.match(rex,hostname):
print (dev[x],'Regex matched')
break
else:
# Does not execute only when a break statement
# is executed inside the for loop.
print('wrong format')
2 Comments
It is printed multiple times, because there are multiple times where the current value does not match. A simple way to fix this is to use a flag, like so:
value_found = False
for x in range(len(regs)):
rex = regs[x]
if re.match(rex,hostname):
print (dev[x],'Regex matched')
value_found = True
break
if not value_found:
print('wrong_format')
Comments
You can maintain a flag variable as follows.
matched = False
for x in range(len(regs)):
rex = regs[x]
if re.match(rex, hostname):
print(dev[x], "Regex matched!")
matched = True
break
if not matched:
print("Wrong format")
Comments
I think you can make it shorter using comprehensive list such as:
if len([r for r in regs if re.match(r, hostname)]) == 1:
print(dev[regs.index([r for r in regs if re.match(r, hostname)][0])], 'Regex matched')
else:
print('not found')
1 Comment
len(...) >= 1. And you would probably also need to change the statement in the print.This should solve your problem.
flag = 0
for x in range(len(regs)):
rex = regs[x]
if re.match(rex, hostname):
print(dev[x], 'Regex matched')
flag = 1
break
if flag == 0:
print('wrong format')