I searched and found ways to check the type of an object but that will not help me in this case. I need to find out if a string CAN be changed to an Integer before actually doing it. I am using pyautogui to grab a region of the screen and save it, then pytesseract open the image, read it, and convert it into a string. Ultimately it is an equation that I would like to solve so then I must change the string into an integer (done in my second function below). At times pytesseract does not read the image correctly so instead of saying something like 5 + 4 it ends up with something like 5 - H, so when my code attempts to turn H into an integer it crashes.
My Question: How can I check to see if for example equation[0] can be made an integer before actually running int(equation[0]) on it and causing my script to crash?
My Code: Simplified greatly to only show the needed lines:
from PIL import Image
import PIL.ImageOps
import pytesseract
import pyautogui
import sys
import time
# --- functions ---
def get_text(image):
return pytesseract.image_to_string(image, config='-psm 6')
def get_int(image):
return int(get_text(image).replace(',', ''))
# --- main ---
#Is equation= needed below or can it be removed?
equation = pyautogui.screenshot('equation.png',region=(845, 262, 240, 85))
img = Image.open('equation.png')
equation = get_text(img)
print ('Equation:',equation)
#Numbers are always single digit (ex. 9-7=) Use slicing to pull numbers and symbol
firstnum = int(equation[0])
sign = equation[1]
secondnum = int(equation[2])
#Adition and Subtraction are the only options
if sign == '-':
answer = firstnum - secondnum
if sign =="+":
answer = firstnum + secondnum
EDIT:
Try and Except seems to be a good way to handle this. Can I somehow turn this into a loop though so it can be checked multiple times. I have found someone used while true as a loop and put try except inside, I am not sure if is will work for me though? Here is how I THINK my Try Except should look? If possible I would like to loop the try until it does not hit an exception.
try:
firstnum = int(equation[0])
except:
equation = pyautogui.screenshot('equation.png',region=(845, 262, 240, 85))
img = Image.open('equation.png')
equation = get_text(img)
firstnum = int(equation[0])
try? You shouldtryto parse it, then catch the exception if it fails. (One of) Python's motto(s) is "it's easier to ask for forgiveness than permission". Let it fail, then clean it up if it does. I'd make that an answer, but my breaks almost over.equation = pyautogui.screenshot('equation.png',region=(845, 262, 240, 85))and that is never used, thenequation = get_text(img). So it's redefined. Are you sure you're trying to index the right thing?