Script Crashing When Trying To Test If A String Is An Integer
Solution 1:
After doing a bit of research I think you can use a try/except block to make sure the value given by the user is actually a number.
try:
i = int(string)
# normal execution
except ValueError:
# error msg
I got the answer here: Converting String to Int using try/except in Python
Solution 2:
You write:
isinstance(
(int(data.GetParam(1).lower())),
int
)
There are two problems with this fragment:
- you call the
int(..)
constructor, and that can fail (error) if you provide it a non-integer (like"foobar18"
); and - in case the constructor succeeds, then it is guaranteed that the outcome is an
int
, so the check is useless.
So now the question is what to do. We can construct an advanced check to inspect if a string is indeed an integer, but the problem is that we have to cover multiple cases, and it is easy to forget one.
Python is a language with the idea: EAFP: Easier to Ask for Forgiveness than Permission. It means that the philosophy of Python is to encourage trying something, and in exceptional cases, handle it, than first check if something is an integer.
So wen can write it as:
if data.IsChatMessage():
try:
int(data.GetParam(1).lower()) # we try it
isint = True # it worked!
except ValueError:
# that did not worked out very well, did it?
isint = False
if (data.GetParam(0).lower() == settings["command"]
and isint
and settings["costs"] <= Parent.GetPoints(data.User):
pass
You better always specify the error you expect to see (ValueError
) since if for instance data.GetParam(1)
raises another error, you do not per se want to handle it there: it does not mean that data.GetParam(1).lower()
is not an integer, it means that data.GetParam(1)
has made some (other) error.
Solution 3:
The line isinstance((int(data.GetParam(1).lower())), int)
will raise a ValueError exception if data.GetParam(1)
is not an integer.
As user8153 suggested, wrap the conversion with try, except block:
try:
int(data.GetParam(1))
print(data.GetParam(1) + 'is an integer')
except ValueError:
print(data.GetParam(1) + 'is not an integer')
Alternatively, you may use data.GetParam(1).isdigit()
Solution 4:
To check if a string can be casted to an int, simply use:
mystr = 'xx12'
if mystr.isnumeric():
print('YES!')
else:
print('NO')
Solution 5:
You can use python built-in string's method .isnumeric()
like this:
>>> "".isnumeric()
False
>>> "a".isnumeric()
False
>>> "5".isnumeric()
True
>>> "55".isnumeric()
True
>>> "55a".isnumeric()
False
but there might be a problem if you also want to check if the number is negative because:
>>> "-5".isnumeric()
False
>>> a = "-4"
>>> a.lstrip("-").isnumeric() and (len(a)-len(a.lstrip("-")) <= 1)
True
>>> a = "--4"
>>> a.lstrip("-").isnumeric() and (len(a)-len(a.lstrip("-")) <= 1)
False
The send part (len(a)-len(a.lstrip("-")) <= 1)
checks if there is more than 1 "-"
s before the number.
Post a Comment for "Script Crashing When Trying To Test If A String Is An Integer"