Python Converting Strings In List To Ints And Floats
If I were to have the following list: lst = ['3', '7', 'foo', '2.6', 'bar', '8.9'] how would I convert all possible items into either ints or floats accordingly, to get lst = [3,
Solution 1:
Loop over each item and make an attempt to convert. If the conversion fail then you know it's not convertible.
deftryconvert(s):
try:
returnint(s)
except ValueError:
try:
returnfloat(s)
except ValueError:
return s
lst = ['3', '7', 'foo', '2.6', 'bar', '8.9']
newlst = [tryconvert(i) for i in lst]
print(newlst)
Output:
[3, 7, 'foo', 2.6, 'bar', 8.9]
Post a Comment for "Python Converting Strings In List To Ints And Floats"