Reputation: 21
I am trying to print the word found in the list from a website response, else if not found print "Not Found". However my script prints the word it found. But it also prints "Not Found" for every item in the list. I just need it to print "Not Found" if nothing from the list found.
My Script:
response = requests.post(URL, headers=Headers, cookies=Cookies, data=Data)
content = response.content
status_type = [b'Approved', b'Pending', b'Rejected', b'Issued']
for status in status_type:
if status in content:
print(status.decode())
if status not in content:
print("Not Found")
Upvotes: 0
Views: 560
Reputation: 654
You can also store your results in another list and print
result = [status.decode() for status in status_type if status in content]
if len(result) == 0:
print("Not Found")
else:
for status in result:
print(status)
Upvotes: 0
Reputation: 6930
The flag approach of paxdiablo's answer is probably the most straightforward; another approach would be to put to gather the found statuses in a list, then handle it:
found_statuses = [status.decode() for status in status_type if status in content]
if found_statuses:
print(', '.join(found_statuses))
else:
print('Not Found')
This would be particularly useful if you needed to take special action if more than one status is found and need to not print them in that case (or print them in a different way):
found_statuses = [status.decode() for status in status_type if status in content]
if len(found_statuses) == 1:
print(found_statuses[0])
elif len(found_statuses) > 1:
print("Conflicting statuses: %s" % ' and '.join(found_statuses))
else:
print('Not Found')
Upvotes: 0
Reputation: 881653
The most obvious approach is simply to use a flag to see if any were found:
found = False
for status in status_type:
if status in content:
print(status.decode())
found = True
# break if you only want the first one found
if not found:
print("Not Found")
Upvotes: 1