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?

khelwood
  • 55,782
  • 14
  • 81
  • 108
lifezbeautiful
  • 1,160
  • 8
  • 13

2 Answers2

3

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

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

Andrew
  • 176
  • 2
  • 8
  • 3
    `is_int_or_str("½")` -> True – 001 Oct 26 '22 at 15:48
  • Added new annotation about inputs like this. Thanks. – Andrew Oct 26 '22 at 15:54
  • Whats wrong with "߂"? This is a number. And int("߂") -> 2. The task does not specify this is incorrect. – Andrew Oct 26 '22 at 16:09
  • Also task need specify limitations of input. This will solve the problem of choosing a method. – Andrew Oct 26 '22 at 16:11
  • 1
    @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)` – lifezbeautiful Oct 26 '22 at 16:43