vandelay vandelay - 1 month ago 11
Python Question

An easy way to turn a string with non integer characters, to an integer

Is there any easy way to turn string like

251.13M
201.41B


Into an integer?

Or is it the rigid approach(Only one I can think of) to find index of '.' and 'M' and do some substringing

Answer

I am pretty sure that there is no direct way(i.e. a single function call) of getting the answer. But you could use a simple code like below.

valD = {"M" : 6, "B" : 9}

def getNumber(nstring):
    if nstring[-1] in valD:
        return int(float(nstring[:-1]) * 10**valD[nstring[-1]])
    else:
        return int(nstring)