Exercise 9.2.9: Strings To Integers5 points
Make a function called safe_int that takes a single argument. This function should try to convert the argument into an integer. If this succeeds, the function should return that integer. Otherwise, the function should return 0.

Then, use this function in a list comprehension to create a list out of the given list. The new list should contain either a 0 or the correct integer in place of every string in the given list:

[0, 2, 7, 0]
Make sure to print out the resulting list.

This is my code so far(i dont know what's wrong with it):
list_of_strings = ["a", "2", "7", "zebra"]


# Your code here...
def safe_int():
list = [int(x) if x.isdigit() else 0 for x in list_of_strings]
print list

safe_int()

but its asking "Function "safe_int" should take exactly 1 argument" and "You should use safe_int in a list comprehension", i dont know how to fix this code please help

Respuesta :

Answer:

x=input("Enter a String")

def safe_int(x):

   #lis1=[ int(x)if x.isdigit() else 0 for x in list_of_strings]

   lis1=[]

   lis1=x.split()

   print(lis1)

   flag=0

   j=0

   while(j in range(len(lis1))):

       if(lis1[j].isdigit()):

           flag==0

       else:

           flag==1

           try:

               if(int(lis1[j])):

                   lis1[j]=int(lis[j])

               else:

                   flag==1

                   break

           except:

               print("Cannot convert to integer")

       j+=1

   print(lis1)    

   

   

safe_int(x)

Explanation:

We are taking as an input a sentence, and then splitting it into various list items, and storing them in a list. Now we try to convert each item to integer and using try-except print the message cannot convert if its not possible or else converts it. As a check. enter 0 2 7 0   and also try Hello World.

Answer:

def safe_int(string):

   return int(string) if string.isdigit() else 0

list_of_strings = ["a", "2", "7", "zebra"]

list_of_numbers = [safe_int(num) for num in list_of_strings] # <-- use the function INSIDE the list comprehension

print(list_of_numbers)

Explanation:

cdoe sh