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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With