Using my dbf package:
import dbf
table = dbf.Table('Cars', default_data_types={'C':dbf.Char}) # don't want extra spaces
cars = []
table.open()
for record in table:
cars.append(record[0]) # or cars.append(record.make) if 'make' is the field name
if len(cars) == 1 and cars[0] == 'empty'):
# print no cars sentence
elif len(cars) == 1:
# print one car sentence
elif len(cars) == 2:
# print two car sentence
else:
# print many car sentence
After the for record in table
loop all the names are in the cars
list. At that point it is simple string substitution:
# many car case
first = "Within this neighborhood there is a "
last = " parked on the street."
middle = ('%s, ' * (len(cars)-1) + 'and a %s') % tuple(cars)
print first + middle + last+
The middle =
line is getting a little fancy with string substitution. Each %s
will be replaced by an entry from cars
, and if you have to have the same number of items in cars
as you have %s
's. And of course you want an 'and' just before the last item. So if you have four cars:
cars = ['Mazda', 'Ford', 'Dodge', 'Yugo']
then
len(cars) - 1 == 3
so
'%s, ' * (len(cars)-1) == '%s, %s, %s, '
and then we add the last part
'%s, ' * (len(cars)-1) + 'and a %s' == '%s, %s, %s, and a %s'
finally, the %
string substitute function sees
'%s, %s, %s, and a %s' % tuple(cars)
which would give us
'Mazda, Ford, Dodge, and a Yugo'
Note: we had to say tuple(cars)
because cars
was a list
and %
needs either a single item or a tuple of items.