Skip to main content
 首页 » 编程设计

python之错误打印字符串 : %d format: a number is required, 不是 str

2025年05月04日20Terrylee

我计划今年夏天晚些时候去迪斯尼世界旅行,我一直在尝试编写一个程序来计算旅行的大概费用,并尽量避免自己变得过于生疏。我的问题是,当我尝试显示所有计算值时,我不断收到标题中的错误。我的代码是:

###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)并且我尝试进行所述更改,但它们对我没有帮助。我可以很好地单独打印每个值,但是当我尝试在这个大文本 block 中全部打印它们时,我会收到错误消息。如果有人提供任何见解,我将不胜感激。

请您参考如下方法:

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

'this is %i' % '5' 

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