How can I check if a string represents an int, without using try/except?

前端 未结 19 1873
悲哀的现实
悲哀的现实 2020-11-22 00:36

Is there any way to tell whether a string represents an integer (e.g., \'3\', \'-17\' but not \'3.14\' or \'asf

相关标签:
19条回答
  • 2020-11-22 01:13

    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:

    1. It doesn't work for various scientific and/or exponential notations (e.g. 1.2E3, 10^3, etc.) - both will return False. I don't think other answers accommodated this either, and even Python 3.8 has inconsistent opinions, since type(1E2) gives <class 'float'> whereas type(10^2) gives <class 'int'>.
    2. An empty string input gives True.
    3. A leading plus sign (e.g. "+7") gives False.
    4. Multiple minus signs are ignored so long as they're leading characters. This behavior is similar to the python interpreter* in that 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.

    0 讨论(0)
提交回复
热议问题