0

For example, I have a list:

l = ["z","u","k","h","r","a","1","2","3"]

How can I check if an element in the list can be int, and if so, convert it to int and replace the str in the list, so that my list would look like

l = ["z","u","k","h","r","a",1,2,3]
DaniiarR
  • 319
  • 1
  • 4
  • 12
  • 2
    please make an attempt before asking and if you run into a problem provide a [mcve] in your question – depperm Oct 24 '18 at 12:12
  • You convert them and handle the exception if it doesn't work. – Klaus D. Oct 24 '18 at 12:12
  • Was adding an answer using list comprehension, but too late... `[x if not x.isnumeric(x) else int(x) for x in l]` – Jab Oct 24 '18 at 12:20

2 Answers2

2

You could write yourself a simple function that tries to convert a value to an integer.

>>> def try_int(x):
...     try:
...         return int(x)
...     except ValueError:
...         return x
... 
>>> l = ["z","u","k","h","r","a","1","2","3"]
>>> [try_int(x) for x in l]
['z', 'u', 'k', 'h', 'r', 'a', 1, 2, 3]

Following the EAFP principle, we just try to convert the value x. That's easier than coding complicated checks in order to find out whether it could be converted.

timgeb
  • 76,762
  • 20
  • 123
  • 145
1

You can use a try-except block around the conversion and ignore the ValueError exceptions:

for i, n in enumerate(l):
    try:
        l[i] = int(n)
    except ValueError:
        pass
blhsing
  • 91,368
  • 6
  • 71
  • 106