Check if a string contains a number

后端 未结 16 1502
無奈伤痛
無奈伤痛 2020-11-22 11:14

Most of the questions I\'ve found are biased on the fact they\'re looking for letters in their numbers, whereas I\'m looking for numbers in what I\'d like to be a numberless

16条回答
  •  無奈伤痛
    2020-11-22 11:43

    You can accomplish this as follows:

    if a_string.isdigit(): do_this() else: do_that()

    https://docs.python.org/2/library/stdtypes.html#str.isdigit

    Using .isdigit() also means not having to resort to exception handling (try/except) in cases where you need to use list comprehension (try/except is not possible inside a list comprehension).

提交回复
热议问题