user1998777
user1998777

Reputation: 169

How to compare two percentages in python?

I am new to python and I am dealing with some csv files. To sort these files, I have to compare some percentages in string format, such as "5.265%" and "2.1545%". So how do I compare the actual values of these two strings? I have tried to convert them to float but it didn't work. Thanks in advance!

Upvotes: 4

Views: 4904

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122262

Still convert them to floats, but without the % sign:

float(value.strip(' \t\n\r%'))

The .strip() removes any extra whitespace, as well as the % percent sign, you don't need that to be able to compare two values:

>>> float('5.265%  '.strip(' \t\n\r%'))
5.265
>>> float('2.1545%'.strip(' \t\n\r%'))
2.1545

float() itself will normally strip away whitespace for you but by stripping it yourself you make sure that the % sign is also properly removed, making this a little more robust when handling data from files.

Upvotes: 7

Related Questions