0

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']
user2774120
  • 139
  • 3
  • 16

3 Answers3

3

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)
yashtodi94
  • 710
  • 1
  • 6
  • 11
1

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']
bfris
  • 5,272
  • 1
  • 20
  • 37
1

Here is your code

b = [float(i) if i.lstrip('-').replace('.', '', 1).isdigit() else i for i in a  ]
print(b)
Dev
  • 387
  • 1
  • 12