打印字符串时出错:%d format:需要一个数字,而不是str

时间:2015-05-11 19:53:15

标签: python python-2.7 format typeerror

我打算今年夏天去迪斯尼乐园旅行,我一直在努力制定一个程序来计算旅行的大概费用,并试图让自己不要太生疏。我的问题是,当我尝试显示所有计算值时,我一直收到标题中的错误。我的代码是:

###Function to display costs
def Display(days, nights, building_type, person, room_cost,
            room_cost_person, DisneyPark, Hopper, IslandPark,
            IslandPTP, Island_parking, gas_cost, gas_cost_person,
            park_person, Total_cost_person, mpg, gas, downpay):
print('''Cost of trip for a %i day/%i night stay in a %%s%%:
Number of people going:                          %i

Total room cost ($)                              %4.2f
Room cost/person ($)                             %4.2f

Price of Disney World tickets ($)                %4.2f
Price of hopper ticket-Disney ($)                %4.2f
Price of Universal ticket ($)                    %4.2f
      Park-to-Park                               %%s%%
Cost to park at Universal/person ($)             %4.2f

Total cost of gas ($)                            %4.2f
Cost of gas/person ($)*                          %4.2f
Cost to park/person ($)                          %4.2f

Cost of groceries/person ($)^                    %4.2f
Cost to eat out/person ($)^#                     %4.2f
Souvenirs ($)^                                   %4.2f

Total cost of trip/person ($)                    %4.2f

*Factoring in round trip distance (1490 miles), mpg of %i, and average gas cost $%4.2f
#Covers eating out at night, eating in parks (butterbeer, etc), and eating while driving
^Note that these are estimates
%Note that the Villa housing requires a $%4.2f downpayment (refundable) that was not
        included in cost calculations

----------------------------------------------------------------------------------------'''
%(day, night, Building, person, room_cost, room_cost_person, DisneyPark,
  Hopper, IslandPark, IslandPTP, Island_parking, gas_cost, gas_cost_person,
  park_person, Groceries, Eat, Souvenirs, Total_cost_person, mpg, gas,
  downpay))

我已经查看了有关此问题的建议:Python MySQLdb issues (TypeError: %d format: a number is required, not str)我试图对所做的更改进行说明,但这对我没有帮助。我可以单独打印每个值,但是当我尝试在这个大块文本中打印它们时,我得到了我的错误。我很感激任何人提供的见解。

3 个答案:

答案 0 :(得分:1)

可能错误是由%i格式之一引起的。例如,以下代码:

'this is %i' % '5'

这将返回相同的错误:TypeError: %d format: a number is required, not str

答案 1 :(得分:0)

您可以在此代码中改进很多内容(阅读评论!)。

尝试根据您要打印的内容更改变量类型:

'Print string as %s, integers as %i ou %d, and float as %4.2f' % \
( '5', int('5'), int('5'), float('5') )

答案 2 :(得分:0)

虽然你的功能有效,但很容易混淆这些功能 参数。这是一个改进版本。我只使用了部分文本,但其余部分应该是直截了当的:

TEMPLATE = """
Cost of trip for a {days} day/{nights} night stay in a %{building_type}%:
Number of people going:                          {person}

Total room cost ($)                              {room_cost:4.2f}
Room cost/person ($)                             {room_cost_person:4.2f}
"""


data = {'days': 3, 'nights': 2, 'building_type': 'hotel', 
        'person': 4, 'room_cost': 80, 'room_cost_person': 20} 

def display_costs(data, template=TEMPLATE):
    """Show the costs in nicely readable format.
    """
    print(template.format(**data))


display_costs(data)    

打印:

Cost of trip for a 3 day/2 night stay in a %hotel%:
Number of people going:                          4

Total room cost ($)                              80.00
Room cost/person ($)                             20.00

我在函数外部的模板中定义了文本。您甚至可以将其定义为额外文件并读取此文件。使用字典data可以帮助您整理数据。我对字符串使用了较新的format()方法。这允许您为占位符使用{}语法。您不需要为字符串和整数定义格式,只要您不希望它们在位置等方面以特殊方式显示它们。可以使用此语法{room_cost:4.2f}指定浮点数的格式。这会给你两个小数,总宽度为4,就像旧% - 格式一样。最后,我在**方法中使用了format()。这相当于编写template.format(days=3, nights=2, ...),除了不必重复字典data中的所有条目。