0

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?

2
  • 1
    Note, isIntStr(" 123 ") is true here. Commented Oct 26, 2022 at 15:49
  • @Andrew, thanks for highlighting, Yes, forgot to add: isIntStr(" 123 ") = True is intended. bcoz later in the pipeline, this is converted to an int, which is the key for some dictionary Commented Oct 26, 2022 at 15:53

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

5 Comments

is_int_or_str("½") -> True
Added new annotation about inputs like this. Thanks.
Whats wrong with "߂"? This is a number. And int("߂") -> 2. The task does not specify this is incorrect.
Also task need specify limitations of input. This will solve the problem of choosing a method.
@Andrew; no other limitations, as I posted: integer within quotes, integer, implying reasonable meaning of integer :) hence cases like "1/2" or "mu" is not needed. I tested your answer and this appears to be much faster, hence I will mark this as accepted, thanks; Yours: 4.75 µs ± 51.4 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) vs Mine: 149 µs ± 1.23 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.