使用我的 dbf 包:
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
在for record in table
循环之后,所有名称都在cars
列表中。那时它是简单的字符串替换:
# 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+
字符串替换使这middle =
条线变得有点花哨。每个都%s
将被替换为来自 的条目,并且如果您cars
必须拥有与 相同数量的项目。当然,您需要在最后一项之前添加一个“和”。所以如果你有四辆车:cars
%s
cars = ['Mazda', 'Ford', 'Dodge', 'Yugo']
然后
len(cars) - 1 == 3
所以
'%s, ' * (len(cars)-1) == '%s, %s, %s, '
然后我们添加最后一部分
'%s, ' * (len(cars)-1) + 'and a %s' == '%s, %s, %s, and a %s'
最后,%
字符串替换函数看到
'%s, %s, %s, and a %s' % tuple(cars)
这会给我们
'Mazda, Ford, Dodge, and a Yugo'
注意:我们不得不说tuple(cars)
因为cars
是一个list
并且%
需要单个项目或项目元组。