Sana ullah
Sana ullah

Reputation: 21

Add value in the last of each row in python

i am new in python. i try to add the integer in the end of each row and save that values in new file. here is current code.

    file = open("Task1.txt","r")
    f1 = open("out.txt", "w+")

    for line in file:
      if not line.lstrip().startswith('#'):
         for l in line.split():
               a = l[0]
               b = l[-1]
               l1= a + b
               s = sum(int(num) for num in l1) 
              for line1 in line:
                 f1.write(line1)

Upvotes: 0

Views: 49

Answers (1)

user12346170
user12346170

Reputation: 98

In the code above, you need to first ensure that l[0] and l[1] are not strings as the l1 = a + b statement will just concatenate them.

If these are expected to be numbers, you can use: a, b = int(l[0]), int(l[1]) or better to use: s = int(l[0]) + int(l[1])

Currently, s = sum(int(num) for num in l1) will add up the digits in l1 and will fail if one of the characters is a letter.

For instance:
If a = '12' and b = '34', l1 will equal 1234, and s will equal 10.
If a = '12' and b = '34a', l1 will equal 1234a, and sum(int(num) for num in l1) will fail as you are trying to make the last character a into an integer.

Upvotes: 1

Related Questions