I need to check if some variable is an integer within quotes. So, naturally, I did the following:
! pip install smartprint
def isIntStr(n):
# first, the item must be a string
if not isinstance(n, str):
return False
# second, we try to convert it to integer
try:
int(n)
return True
except:
return False
from smartprint import smartprint as sprint
sprint (isIntStr("123_dummy"))
sprint (isIntStr("123"))
sprint (isIntStr(123))
It works as expected with the following output:
isIntStr("123_dummy") : False
isIntStr("123") : True
isIntStr(123) : False
Is there a cleaner way to do this check?
CodePudding user response:
I think this solution be better.
def is_int_or_str(x):
if isinstance(x, str):
return x.strip().isnumeric()
else:
return False
print(f"Check '123': {is_int_or_str('123')}")
print(f"Check ' 123 ':{is_int_or_str(' 123 ')}")
print(f"Check '123abc': {is_int_or_str('123abc')}")
print(f'Check 123: {is_int_or_str(123)}')
Output:
Check '123': True
Check ' 123 ': True
Check '123abc': False
Check 123: False
If input like "½" or something should be False change .isnumeric() method on .isdigit()
CodePudding user response:
You could also use the any()
function together with the isDigit()
function as shown in this answer https://stackoverflow.com/a/19859308/12373911