I have a list of mixed types of data:
list = ['Diff', '', '', 0, ' 16.67%', ' 2.81%', 0, ' 13.33%']
I only want to convert the numerical strings in this list to Integers/float, so my list will be:
newlist = ['Diff', '', '', 0, 16.67%, 2.81%, 0, 13.33%]
I know this res = [eval(i) for i in list]
can convert all the strings to integers if everything in my list is numerical strings, but how do I do to only convert the numerical strings in a mixed-type list?
CodePudding user response:
This is one way of doing that by checking if the str isnumeric and type cast to int if it is a numeric value.
list = ['1', 'yes', 'diff', '43', '2', '4']
print(list)
for i, n in enumerate(list):
if n.isnumeric():
list[i] = int(n)
print(list)
CodePudding user response:
When doing type conversions in python, you attempt a conversion first and provide a reasonable fallback for the case it fails ("ask forgiveness, not permission"). There are just too many things that can go wrong with a conversion, and it's hard to check them all in advance.
def maybe_int(x):
try:
return int(x)
except (TypeError, ValueError):
return x
lst = ['1', 'yes', 'diff', '43', '2', '4']
print([maybe_int(x) for x in lst])
CodePudding user response:
I think you can use try-except:
for i in range(len(array)):
try:
array[i] = int(array[i])
except:
print("Can not cast this element to int") # you can write nothing here
More info about try-except here