Instead of printing toy[0] immediately, use an if-else statement to check if there is a toy before printing to the console. If there is no toy, print "No toy found".
Based on the code sample you supplied, the solution would look like this:
import re
file = open("example.txt","r")
content = file.read()
file.close()
car = re.findall('car\s(.*?)\s',open('example.txt','r').read())
toy = re.findall('toy\s(.*?)\s',open('example.txt','r').read())
if toy:
print toy[0]
else:
print 'No toy found'
if car:
print car[0]
else:
print 'No car found'
Note that while this solution may work, there are some improvements that can be made to your code overall.
The improvements include:
- Using the Python
with statement to easily close the file you opened
- Avoid using a variable named
find as it is a keyword in Python and may lead to unexpected behavior later in your application
- Using the data you've saved in the
content variable for the regular expression match (so that you don't have to read from the file again).
The improvements will leave you with code that looks like this:
import re
#use with statement to open and close file cleanly
with open('example.txt','r') as f:
# save file contents in the content variable so you don't need to open the file again
content = f.read()
# use data stored in content variable for your regular expression match
car = re.findall('car\s(.*?)\s',content)
toy = re.findall('toy\s(.*?)\s',content)
if toy:
print toy[0]
else:
print 'No toy found'
if car:
print car[0]
else:
print 'No car found'
if toy: print toy[0] else: print 'No toy found'