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

前端 未结 19 1845
悲哀的现实
悲哀的现实 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 00:52

    The proper RegEx solution would combine the ideas of Greg Hewgill and Nowell, but not use a global variable. You can accomplish this by attaching an attribute to the method. Also, I know that it is frowned upon to put imports in a method, but what I'm going for is a "lazy module" effect like http://peak.telecommunity.com/DevCenter/Importing#lazy-imports

    edit: My favorite technique so far is to use exclusively methods of the String object.

    #!/usr/bin/env python
    
    # Uses exclusively methods of the String object
    def isInteger(i):
        i = str(i)
        return i=='0' or (i if i.find('..') > -1 else i.lstrip('-+').rstrip('0').rstrip('.')).isdigit()
    
    # Uses re module for regex
    def isIntegre(i):
        import re
        if not hasattr(isIntegre, '_re'):
            print("I compile only once. Remove this line when you are confident in that.")
            isIntegre._re = re.compile(r"[-+]?\d+(\.0*)?$")
        return isIntegre._re.match(str(i)) is not None
    
    # When executed directly run Unit Tests
    if __name__ == '__main__':
        for obj in [
                    # integers
                    0, 1, -1, 1.0, -1.0,
                    '0', '0.','0.0', '1', '-1', '+1', '1.0', '-1.0', '+1.0',
                    # non-integers
                    1.1, -1.1, '1.1', '-1.1', '+1.1',
                    '1.1.1', '1.1.0', '1.0.1', '1.0.0',
                    '1.0.', '1..0', '1..',
                    '0.0.', '0..0', '0..',
                    'one', object(), (1,2,3), [1,2,3], {'one':'two'}
                ]:
            # Notice the integre uses 're' (intended to be humorous)
            integer = ('an integer' if isInteger(obj) else 'NOT an integer')
            integre = ('an integre' if isIntegre(obj) else 'NOT an integre')
            # Make strings look like strings in the output
            if isinstance(obj, str):
                obj = ("'%s'" % (obj,))
            print("%30s is %14s is %14s" % (obj, integer, integre))
    

    And for the less adventurous members of the class, here is the output:

    I compile only once. Remove this line when you are confident in that.
                                 0 is     an integer is     an integre
                                 1 is     an integer is     an integre
                                -1 is     an integer is     an integre
                               1.0 is     an integer is     an integre
                              -1.0 is     an integer is     an integre
                               '0' is     an integer is     an integre
                              '0.' is     an integer is     an integre
                             '0.0' is     an integer is     an integre
                               '1' is     an integer is     an integre
                              '-1' is     an integer is     an integre
                              '+1' is     an integer is     an integre
                             '1.0' is     an integer is     an integre
                            '-1.0' is     an integer is     an integre
                            '+1.0' is     an integer is     an integre
                               1.1 is NOT an integer is NOT an integre
                              -1.1 is NOT an integer is NOT an integre
                             '1.1' is NOT an integer is NOT an integre
                            '-1.1' is NOT an integer is NOT an integre
                            '+1.1' is NOT an integer is NOT an integre
                           '1.1.1' is NOT an integer is NOT an integre
                           '1.1.0' is NOT an integer is NOT an integre
                           '1.0.1' is NOT an integer is NOT an integre
                           '1.0.0' is NOT an integer is NOT an integre
                            '1.0.' is NOT an integer is NOT an integre
                            '1..0' is NOT an integer is NOT an integre
                             '1..' is NOT an integer is NOT an integre
                            '0.0.' is NOT an integer is NOT an integre
                            '0..0' is NOT an integer is NOT an integre
                             '0..' is NOT an integer is NOT an integre
                             'one' is NOT an integer is NOT an integre
     is NOT an integer is NOT an integre
                         (1, 2, 3) is NOT an integer is NOT an integre
                         [1, 2, 3] is NOT an integer is NOT an integre
                    {'one': 'two'} is NOT an integer is NOT an integre
    
        

    提交回复
    热议问题