How to check if the value of a string variable is a number?
In this article, we’ll learn how to check if the value of a string variable is a number with Python, in very simple and quick ways.
What’s up programmer, okay? Let’s learn more about Python!
We have a method in Python that checks whether strings are a digit, but it only works with positive integers.
The method is “isdigit”, it will return True or False if the string is an integer, take a look:
a = 'test' b = '12' c = 'we have number 1 here' print(a.isdigit()) print(b.isdigit()) print(c.isdigit())
Here we see the method being used, see the outputs:
False True False
Note that it will only return True if the string is really just a number.
In other cases, False is returned.
We can also make a function to handle this case, and cover the floats (broken numbers), see:
d = '12.28' e = 'test' def isNumber(n): try: float(n) except ValueError: return False return True print(isNumber(d)) print(isNumber(e))
Here we will have more flexibility regarding the inputs, see the output of this code:
You just have to choose who has the most applicability in your business rule
And if I could indicate you any way, I would take the first one
Since it is a native Python alternative and it will definitely give you better performance than our function with try
Always choose alternatives for the language you are using and always look for native functions for what you are trying to do, there must be something already created or similar
In this article, we learned how to check if the value of a string variable is number
In a simpler way with “isdigit”, but it doesn’t cover floats
And another through a function that handles any type of input, returning values for floating points as well
Want to learn more about Python? Click here!