【问题标题】:Python Error: Not all arguments converted during string formattingPython 错误:字符串格式化期间并非所有参数都转换了
【发布时间】:2016-10-17 19:09:58
【问题描述】:
def process_cars(text_file):
    total_cmpg = 0
    for line in text_file:
        if((line % 2) == 0):
            city_mpg = (line[52:54])
            print(city_mpg)
            city_mpg = int(city_mpg)
            total_cmpg += city_mpg
    print ("Total miles per gallon in the city:", total_cmpg)

错误出现在 if((line % 2) == 0): 我已经搜索了具有相同错误的其他问题,但没有一个可以解决问题。错误是:在字符串格式化期间并非所有参数都转换了。我想修改线条的位置。例如,如果是第三行,则为 2 % 2。

【问题讨论】:

  • 你想用line % 2做什么你想修改线路中的数字吗?
  • 我正在尝试调整线条的位置。如果是第三行,那么 2 % 2 @MooingRawr

标签: python python-3.x


【解决方案1】:
def process_cars(text_file):
    total_cmpg = 0
    for file_line_number, line in enumerate(text_file):
        if((file_line_number % 2) == 0):
            city_mpg = (line[52:54])
            print(city_mpg)
            city_mpg = int(city_mpg)
            total_cmpg += city_mpg
    print ("Total miles per gallon in the city:", total_cmpg)

根据您的 cmets,您只想每隔 x 行执行一次 if 语句。试试我们上面的内容,因为我们使用的是enumerate(),它记录了对象中接下来的内容。在我们的例子中,它保持行号的计数,同时仍然给我们行是什么。

file_line_number是当前文件号行,line是行内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-05
    • 1970-01-01
    • 2010-11-08
    • 2022-01-10
    • 2015-01-21
    • 1970-01-01
    相关资源
    最近更新 更多