example_strings = ["10.43 KB", "11 GB", "343.1 MB"]
I want to convert all this strings into bytes. So far i came up with this:
def parseSize(size):
if size.endswith(" B"):
size = int(size.rstrip(" B"))
elif size.endswith(" KB"):
size = float(size.rstrip(" KB")) * 1000
elif size.endswith(" MB"):
size = float(size.rstrip(" MB")) * 1000000
elif size.endswith(" GB"):
size = float(size.rstrip(" GB")) * 10000000000
elif size.endswith(" TB"):
size = float(size.rstrip(" TB")) * 10000000000000
return int(size)
but I don't like it and also I don't think it works. Is there any python module that can help me? I could find only modules that do the opposite thing.
To answer the OPs question, there does seem to be a module for this, humanfriendly:
pip install humanfriendly
then,
The code searches for the unit of measure that contains the string. once found. with another regular expression, extract the number. once done these two things. calculate the value to bytes. if the value is not specified, it tries to treat it as Bytes but the function returns 0 if not possible conversion.
Here's a slightly prettier version. There's probably no module for this, just define the function inline. It's very small and readable.
I liked Denziloe's answer compared to everything else that came up in google, but it
kb
was 1000 instead of 1024, etc. (Kudos to mlissner for trying to point that out years ago. Maybe our assumptions are too old school, but I don't see most software catching up to the new assumptions either.)So I tweaked it into this:
which we can verify by checking the output: