-1

I have this list:

array = ['Katherine', '999', '333']

I need to convert the '999' and '333' into floats.

The list should look like this after:

array = ['Katherine', 999.0, 333.0]
jwpfox
  • 5,124
  • 11
  • 45
  • 42
  • 2
    So convert them, `float(str)` converts a string to a float. – AChampion Dec 07 '16 at 01:30
  • 1
    Possible duplicate of [Python convert string to float](http://stackoverflow.com/questions/29219479/python-convert-string-to-float) – abronan Dec 07 '16 at 02:24
  • I improved the formatting of your question to make it easier to read. Please review Stack Overflow's formatting documentation in the [help centre](https://stackoverflow.com/help/formatting) so you can do this yourself next time. Good luck! – ChrisGPT was on strike Dec 07 '16 at 13:18
  • What you have is a list. You will help yourself learning Python if you use the right names for the things you are working with. – jwpfox Dec 10 '16 at 23:30

1 Answers1

0

Yeah, float(s) can do this. Here is the code.

array = ['Katherine', '999', '333']

def is_number(s):
    """ Returns True if the string is a number. """
    try:
        float(s)
        return True
    except ValueError:
        return False

print(array)

// for i, v in enumerate(array):
//     if is_number(v):
//         array[i] = float(v)

array = list(map(is_number, array))

print(array)
Jacob
  • 561
  • 4
  • 9
  • 1
    Better yet, have `is_number` return the float value *if possible* or the original value otherwise (and rename the function to `try_parse` or something like that). All that remains to be done then is: `array = list(map(try_parse, array))`. – UltraInstinct Dec 10 '16 at 23:33