Better way to check if variable is string of integer

Question:

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?

Asked By: lifezbeautiful

||

Answers:

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()

Answered By: Andrew

You could also use the any() function together with the isDigit() function as shown in this answer https://stackoverflow.com/a/19859308/12373911

Answered By: Malik Meshi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.