I have below python list
a= ['2','3','44','22','cat','2.2','-3.4','Mountain']
How can i get below output with one command (convert only numeric strings to numeric)
a = [2,3,44,22,'cat',2.2,-3.4,'Mountain']
I have below python list
a= ['2','3','44','22','cat','2.2','-3.4','Mountain']
How can i get below output with one command (convert only numeric strings to numeric)
a = [2,3,44,22,'cat',2.2,-3.4,'Mountain']
Try converting to integer if numeric. For floats convert it blindly and if there is an exception, we can assume its a string.
foo = []
for i in a:
if i.isnumeric():
foo.append(int(i))
else:
try:
foo.append(float(i))
except ValueError:
foo.append(i)
print(foo)
Output:
[2, 3, 44, 22, 'cat', 2.2, -3.4, 'Mountain']
UPDATE A shorter version of the code would be:
foo = []
for i in a:
try:
foo.append(int(i) if float(i).is_integer() else float(i))
except ValueError:
foo.append(i)
print(foo)
The brute force way to do it is to go through the whole list and convert item by item. If the conversion fails, it will raise a ValueError exception which you can catch.
a= ['2','3','44','22','cat','2.2','-3.4','Mountain']
# enumerate is a handy function which gives you both the index and item for the
# contents of an iterable.
for i, item in enumerate(a):
try:
a[i] = int(float(item))
except ValueError:
a[i] = item
print(a)
which gives
[2, 3, 44, 22, 'cat', 2, -3, 'Mountain']
Here is your code
b = [float(i) if i.lstrip('-').replace('.', '', 1).isdigit() else i for i in a ]
print(b)