Changing strings into integers
<p>I'm going crazy and I can not figure the right solution :(</p>

<p>How can I solve that problems. I have a loop and I can get diffrent types like:</p>

<pre><code>empty string
10
10K
2.3K
2.34K
2M
2.2M
2.23M
</code></pre>

<p>I need to change them into numbers:</p>

<pre><code>0
10
10000
2300
2340
2000000
2200000
2230000
</code></pre>

<p>Your steps should be:</p>

<ul>
<li>check if string is empty

<ul>
<li>return 0</li>
</ul></li>
<li>check if string ends in K or M

<ul>
<li>if it does, strip that character off the end, store it for later</li>
<li>multiply by appropriate factor (K = 1000 or M = 1000000)</li>
</ul></li>
</ul>

<p>This can be achieved with the following:</p>

<pre><code>def convert(value):
    if value:
        # determine multiplier
        multiplier = 1
        if value.endswith('K'):
            multiplier = 1000
            value = value[0:len(value)-1] # strip multiplier character
        elif value.endswith('M'):
            multiplier = 1000000
            value = value[0:len(value)-1] # strip multiplier character

        # convert value to float, multiply, then convert the result to int
        return int(float(value) * multiplier)

    else:
        return 0

values = [
    '',
    '10',
    '10K',
    '2.3K',
    '2.34K',
    '2M',
    '2.2M',
    '2.23M',
]

# use a list comprehension to call the function on all values
numbers = [convert(value) for value in values]

print numbers
</code></pre>

<p>This should return</p>

<pre><code>[0, 10, 10000, 2300, 2340, 2000000, 2200000, 2230000]
</code></pre>

python regex python-2.7