0

I have a file I'm working with that has an integer per line and no commas are separating the numbers. When I go to get the sum of the numbers in that file, it only works for positive integers. What I have doesn't work for negative numbers in the file. Any way of being able to accomplish that? My code in question:

if line.strip().isdigit():
            total += int( line)

If all the numbers in the file are negative, it'll just return the sum as 0. What other method of achieving the same goal (sum of all numbers in file) could I use that would work to add positive and negative integers?

Nick
  • 97
  • 3
  • 11
  • Possible duplicate of [How to type negative number with .isdigit?](http://stackoverflow.com/questions/28279732/how-to-type-negative-number-with-isdigit) – David Gourde Apr 11 '16 at 02:19
  • Is there anything else in your file besides integers? If not, the isdigit() check would be unnecessary. If yes, what else can be found in it? – Markus M. Apr 11 '16 at 02:54
  • @MarkusM. There isn't anything other than integers in the file of what I'm trying to get the sum of . – Nick Apr 11 '16 at 02:59

2 Answers2

1

The problem is that those methods require all characters be a digit, and - is not; see https://docs.python.org/2/library/stdtypes.html

>>> "234".isalnum()
True
>>> "-234".isalnum()
False
>>> "-234".isalpha()
False
>>> "-234".isdigit()
False

If your file contains int and non-ints, then maybe see is_number(s): How do I check if a string is a number (float) in Python? but modify it for int. Something like:

def is_number(s):
    try:
        int(s)
        return True
    except ValueError:
        return False

and then use is_number where you have is_digit.

Community
  • 1
  • 1
Tommy
  • 12,588
  • 14
  • 59
  • 110
  • I'm trying to not import things. Is there any other form of doing this without importing anything? – Nick Apr 11 '16 at 02:17
  • But wouldn't this just ignore the negative numbers in the txt file I'm getting my numbers from? It doesn't add them up like I'm aiming for? Also I'm just looking integers. – Nick Apr 11 '16 at 02:27
1

how about

try: total += int(line) except: pass

rhinoxi
  • 111
  • 2
  • 6
  • This would just totally by pass adding the numbers together if they aren't positive, wouldn't it? – Nick Apr 11 '16 at 02:23
  • Hi @Nick, int('-123') will work correctly. I think you just need to concern whether it is legal to convert to an int. – rhinoxi Apr 11 '16 at 02:30