Grant Caley
Grant Caley

Reputation: 1

Cant workout how to compare two string decimals in numeric equation

Python 2.7.9

I have two strings that I've extracted from AWS Billing reports

e.g. 1.14 and 2.75

I'm parsing a string line by line and dropping these values into a var (they appear in set positions after the word 'Maximum' and before a last comma.

e.g.

from decimal import *
for line in output.split('\n'):
        top_answer = 0
        if "Maximum" in line:
                ext = line.strip()[10:-1]
                ans = Decimal(ext)
                print(ext,top_answer)
                if ans > top_answer:
                        top_answer = ans
print(top_answer)

The output is:

(' 1.46', 0) (' 1.37', 0) (' 1.3', 0) 0

I've tried using floats (that was scary and didn't work), I've tried comparing the strings, but that obviously didn't work. I'm now on decimals, but really struggling. Everything I try returns that ext>top_answer, which it is not.

Any ideas on how to do this, virtually every other language I've used was a lot easier.

BTW im a part time programmer for my home automation delight, so don't give me too hard a time about my programming lazyness :)

Thanks.

Upvotes: 0

Views: 16

Answers (1)

Patrick Artner
Patrick Artner

Reputation: 51643

You are resetting top_answer to 0 all the time

from decimal import *
for line in output.split('\n'):
        top_answer = 0                  # set to zero on each begin of line
        if "Maximum" in line:
                ext = line.strip()[10:-1]
                ans = Decimal(ext)
                print(ext,top_answer)
                if ans > top_answer:
                    # whatever, top_answer will be replaced by 0 anyway.

You should put top_answer=0 before the loop. Your last line in output does not contain any "Maximum" - but the top_answer will be reset to 0 non the less - so you only ever get zeros for it.

In python 2.x you do not need parenthesis arount print btw - thats why you get a "tuple" like output

Upvotes: 1

Related Questions