1

我得到这本书来帮助我的学习,但是即使它“涵盖”了python 3,这只是后面的一小部分,在你相当熟练(我想)之前没有太大帮助,我在第 3 章使用字符串,我的代码不起作用。我在书籍代码中发现了一些问题并更新了代码,现在我让它开始运行,但我得到:

Traceback(最近一次通话最后):文件“C:/Users/Garan/Desktop/Portfolio/String Formatting.py”,第 15 行,打印中(格式 %(item_width,'Apples',price_width,0.4))ValueError:不支持索引 2 处的格式字符 '/' (0x2f)

我在代码中看不到 / 字符。也许那是用来指定其他东西的,我不确定。下面是我的代码,希望有人能引导我走上正确的道路。

# Print a formatted price list with a given width
width = int(input('Please enter width: '))

price_width = int(10)
item_width = int(width - price_width)

header_format = '%-*s%*s'
format = '%-/s%*.2f'

print ('=' * width)
print (header_format % (item_width, 'Item', price_width, 'Price'))

print ('-' * width)

print (format % (item_width, 'Apples', price_width, 0.4))
print (format % (item_width, 'Pears', price_width, 0.5))
print (format % (item_width, 'Cantaloupes', price_width, 1.92))
print (format % (item_width, 'Dried Apricots (16 oz.', price_width, 8))
print (format % (item_width, 'Prunes (4 lbs.)', price_width, 12))

print ('=' * width)
4

1 回答 1

3

你有一个/这里:

format = '%-/s%*.2f'

用。。。来代替:

format = '%-s%*.2f'
于 2015-05-23T11:32:45.617 回答