在拆分字符串后将字符串转换为整数?

时间:2014-06-11 22:15:54

标签: python

import math

def main():
    StrFileName = input('Enter a File')
    inFile = open(StrFileName, 'r')
    intLines = 0

    for i in open(StrFileName, 'r'):
        intLines = intLines + 1

    intTotalLines = intLines
    intID = 0
    intAmt = 0
    intIncome = 0
    State = 0

    for i in range(intTotalLines):
        line = inFile.readline()
        intID, intAmt, intIncome, State = line.split()
        Line = [intID, intAmt, intIncome, State]
        Income = int(intIncome)
        print(sum(Income))

main()

我在尝试将int object is not iterable转换为intIncome时会不断收到消息int(行拆分自动使其成为字符串)。提前感谢您的帮助!

3 个答案:

答案 0 :(得分:5)

您的错误来自使用参数sum调用IncomeIncome已经是一个整数,所以只需打印它:

print(Income)

答案 1 :(得分:2)

如果您试图从每一行获得收入总和,您可以构建一个列表并对其求和,或者保持一个总计如下:

totalIncome = 0

for i in range(intTotalLines):

        line = inFile.readline()

        intID, intAmt, intIncome, state = line.split()

        totalIncome += int(intIncome)

print(totalIncome)

答案 2 :(得分:1)

def main():
    str_file_name = input("Enter a File")
    with open(str_file_name, 'r') as in_file: # use with to open your files as it closes them automatically
        int_lines = 0

        for i in open(str_file_name, 'r'):
            int_lines += 1
        int_total_lines = int_lines

        for i in range(int_total_lines):
            lines = in_file.readline()
            int_id, int_amt, int_income, state = lines.split()
            income = int(int_income)
            print(income)
main()

我编写了代码,其中包含如何命名变量的示例,不应使用大写字母表示变量名称,int_lines += 1int_lines = int_lines + 1的简写。

我删除了一些未使用的变量,但我只想向您展示一些样式提示,以使您的代码更具可读性并符合python style guide