Anna K Anna K - 2 months ago 8
Python Question

Changing strings into integers

I'm going crazy and I can not figure the right solution :(

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

empty string
10
10K
2.3K
2.34K
2M
2.2M
2.23M


I need to change them into numbers:

0
10
10000
2300
2340
2000000
2200000
2230000

Answer

Your steps should be:

  • check if string is empty
    • return 0
  • check if string ends in K or M
    • if it does, strip that character off the end, store it for later
    • multiply by appropriate factor (K = 1000 or M = 1000000)

This can be achieved with the following:

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

This should return

[0, 10, 10000, 2300, 2340, 2000000, 2200000, 2230000]