Does anybody have a quickie for converting an unsafe string to an int
?
The string typically comes back as: \'234\\r\\n\'
or something like
Under Python 3.0 (IDLE) this worked nicely
strObj = "234\r\n"
try:
#a=int(strObj)
except ValueError:
#a=-1
print(a) >>234
If you're dealing with input you cannot trust, you never should anyway, then it's a good idea to use try, except, pass blocks to control exceptions when users provide incompatible data. It might server you better to think about try, except, pass structures as defensive measures for protecting data compatibility rather than simply hidding errors.
try:
a=int(strObj) #user sets strObj="abc"
except ValueError:
a=-1if a != -1:
#user submitted compatible data
else:
#inform user of their error
I hope this helps.