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)
type(res)
does not return what you think it does:As you can see, it returns the type object for floats, not the string
"float"
. You can read about this behavior in the docs:That said, you can greatly simplify your function by using a list comprehension:
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.