Python Forum

Full Version: converting data sizes like: 4k, 32k, 4m, 16m, 1g, etc
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i had asked if there was a Python library function to do this, which i could not find. there was no answer, so i had to implement my own. this is not yet tested:
_intsi_powers={'k':1,'m':2,'g':3,'t':4,'p':5,'e':6}
def intsi(digits='0',base=10,multi=1024,empty=None,invalid=None):
    """Convert numbers with suffixes for SI units (metric)."""
    if not digits:
        return empty
    scale=1
    if digits[-1] in _intsi_powers:
        scale=multi**_intsi_powers[digits[-1]]
        digits=digits[:-1]
        if not digits:
            return empty
    try:
        return scale*int(digits,base)
    except ValueError:
        return invalid