Search code examples
pythonlisttypechecking

Convert only float in the mixed type list


I have the following list:

ls1 = ['xxx', 3.88884, 2.383, 1.999, '-']

what I want to do is to convert the float value into "%.2f", resulting this:

['xxx', '3.88', '2.38', '1.99', '-']

But why this code failed?

def stringify_result_list(reslist):
    finals = []
    print reslist
    for res in reslist:
        if type(res) == 'float':
           tmp = "%.2f" % res
           finals.append(tmp)
        else:
           finals.append(res)
    print finals
    return finals

 stringify_result_list(ls1)

Solution

  • type(res) does not return what you think it does:

    >>> type(1.0)
    <type 'float'>
    >>> type(type(1.0))
    <type 'type'>
    >>>
    

    As you can see, it returns the type object for floats, not the string "float". You can read about this behavior in the docs:

    class type(object)
    class type(name, bases, dict)

    With one argument, return the type of an object. The return value is a type object. The isinstance() built-in function is recommended for testing the type of an object.


    That said, you can greatly simplify your function by using a list comprehension:

    def stringify_result_list(reslist):
        return ["%.2f" % x if isinstance(x, float) else x for x in reslist]
    

    You'll notice too that I used isinstance to test whether each item is a float. As the quote above says, this is the preferred method of typechecking in Python.