+ 2

Check if String is an Integer

Hey! I saw that there is a special method to check if a string is an integer: .isdigit() but I can‘t use it. Do I have to import a special library for that? It seems like the interpreter doesn’t know that method...

20th Mar 2018, 6:23 PM
Patrick Exner
Patrick Exner - avatar
3 Réponses
+ 7
It should work without modules. Try the following: st = "123" bool = st.isdigit() print(bool) if bool: print("runs")
20th Mar 2018, 6:26 PM
Pedro Demingos
Pedro Demingos - avatar
+ 8
def RepresentsInt(s): try: int(s) return True except ValueError: return False >>> print RepresentsInt("+123") True >>> print RepresentsInt("10.0") False
20th Mar 2018, 6:36 PM
Baraa AB
Baraa AB - avatar
+ 3
@Pedro Demingos Thanks! It works. I hope it will in my project too
20th Mar 2018, 6:35 PM
Patrick Exner
Patrick Exner - avatar