Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 708
user1998777 Avatar asked Mar 23 '23 18:03

user1998777


1 Answers

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.

like image 123
Martijn Pieters Avatar answered Apr 02 '23 21:04

Martijn Pieters