Home > database >  Writing a loop that removes units from strings
Writing a loop that removes units from strings

Time:04-01

def convert_gravity_value(value):
    """Convert a planet's "gravity" value to a float. Removes the "standard" unit of measure if
    it exists in the string. Delegates to the function < convert_to_float > the task of casting
    the < value > to a float.

    Parameters:
        value (obj): string to be converted

    Returns:
        float: if value successfully converted; otherwise returns value unchanged
    """
    try:
        for this in value:
            if this['standard']:
                value.remove(this['standard'])
                return convert_to_float(value)
    except:
        return value
// Where covert_to_float is just "return float(value)"

I have the following list: ['1 standard', '2 standard', '2.5', '3 standard', '3.56']

And I'm trying to write a function that takes in the list as a parameter so that it returns 1.0, 2.0, 2.5, 3.0, 3.56. If the 'standard' unit exists, it should be removed; else, the element should be directly converted to a float.

CodePudding user response:

You can loop over each list element, and use .split() to extract the individual tokens. You can then use a try/except to convert each word into a floating point value:

data = ['1 standard', '2 standard', '2.5', '3 standard', '3.56']

result = []
for item in data:
    words = item.split()
    for word in words:
        try:
            result.append(float(word))
        except ValueError:
            # We may see some words which aren't numbers;
            # this is expected, so we do nothing upon catching this error.
            pass

print(result)

This outputs:

[1.0, 2.0, 2.5, 3.0, 3.56]

CodePudding user response:

li = ['1 standard', "2", '3 standard', '6.44']
for index, item in enumerate(li):
   if 'standard' in item:
      st_ind = item.find('standard')
      li[index] = float(item[0:st_ind - 2]) # - 2 because you need to slice before the start of space (1 for s and 1 for space)
   else:
      li[index] = float(item)

This is what I think you're trying to do.

  • Related