Is there any way to tell whether a string represents an integer (e.g., \'3\'
, \'-17\'
but not \'3.14\'
or \'asf
I do this all the time b/c I have a mild but admittedly irrational aversion to using the try/except pattern. I use this:
all([xi in '1234567890' for xi in x])
It doesn't accommodate negative numbers, so you could strip out all minus signs on the left side, and then check if the result comprises digits from 0-9:
all([xi in '1234567890' for xi in x.lstrip('-')])
You could also pass x to str() if you're not sure the input is a string:
all([xi in '1234567890' for xi in str(x).lstrip('-')])
There are some (edge?) cases where this falls apart:
type(1E2)
gives <class 'float'>
whereas type(10^2)
gives <class 'int'>
.type(---1)
returns <class int>
. However, it isn't completely consistent with the interpreter in that int('---1')
gives an error, but my solution returns True
with the same input.So it won't work for every possible input, but if you can exclude those, it's an OK one-line check that returns False
if x is not an integer and True
if x is an integer. But if you really want behavior that exactly models the int()
built-in, you're better off using try/except.
I don't know if it's pythonic, but it's one line, and it's relatively clear what the code does.
*I don't mean to say that the interpreter ignores leading minus signs, just that any number of leading minus signs does not change that the result is an integer. int(--1)
is actually interpreted as -(-1)
, or 1. int(---1)
is interpreted as -(-(-1))
, or -1. So an even number of leading minus signs gives a positive integer, and an odd number of minus signs gives a negative integer, but the result is always an integer.