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

前端 未结 19 1856
悲哀的现实
悲哀的现实 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:01

    str.isdigit() should do the trick.

    Examples:

    str.isdigit("23") ## True
    str.isdigit("abc") ## False
    str.isdigit("23.4") ## False
    

    EDIT: As @BuzzMoschetti pointed out, this way will fail for minus number (e.g, "-23"). In case your input_num can be less than 0, use re.sub(regex_search,regex_replace,contents) before applying str.isdigit(). For example:

    import re
    input_num = "-23"
    input_num = re.sub("^-", "", input_num) ## "^" indicates to remove the first "-" only
    str.isdigit(input_num) ## True
    

提交回复
热议问题