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