1

How can i write the code for an if condition where i want to see if i can convert the type of an element in a list to int. If its possible, then if condition should be executed.Otherwise, it should go to else statement

For eg:

lst=['@','#','^','%','20']

''' Now i am going to iterate through the list and check if i can convert the elements  to type int. If it can be converted then i know there is a number in the list and i do some operations on the number'''

for ele in lst:
    if(type(int(ele)=='int'):
        #do some operation on the number eg:20/2 and print the value
    else:
        continue

Please give me an idea as to how to write the if condition.

loginator
  • 11
  • 3
  • 1
    You should instead `try` to convert the element to int and proceed if successful, `except` that you do something else when that fails with a `ValueError`. – Karl Knechtel Nov 15 '20 at 17:09
  • Does this answer your question? [Python: Test if value can be converted to an int in a list comprehension](https://stackoverflow.com/questions/5606585/python-test-if-value-can-be-converted-to-an-int-in-a-list-comprehension) – Mickey Nov 15 '20 at 17:14

4 Answers4

1

Try to convert to int and catch the error:

for ele in lst:
    try:
        val = int(ele)
    except ValueError:
        continue
    else:
        print(val)
Christian K.
  • 2,785
  • 18
  • 40
0

Try with .isdigit()+a list comprehension (perfect couple ;-):

lst=['@','#','^','%','20']
[str(x).isdigit() for x in lst]

Caveat: does not work for float strings, for floats:

[str(x).replace('.','').isdigit() for x in lst]
Wasif
  • 14,755
  • 3
  • 14
  • 34
0

You could check if each element is an int using a try block in a helper function is_int:

def is_int(s):
    try: 
        int(s)
        return True
    except ValueError:
        return False

lst = ['@', '#', '^', '%', '20']
for s in lst:
    if is_int(s):
        int_s = int(s)
        print(f'{int_s}/2 = {int_s/2}')
    else:
        continue

Output:

20/2 = 10.0
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
0

I think what you are looking for is :

if isinstance(ele,int)
lst = ['@', '#', '^', '%', 20]

for ele in lst:
    if isinstance(ele,int):
        print("This is int: " + str(ele))
    else:
        print("This is not int: " + ele)

Very simple and easy.

IceJonas
  • 720
  • 6
  • 13