How to check if string contains numbers in Python?
I have a variable which I am convert to float, but I want to make if statement, to convert it to float only if it contains only numbers.
How to check if string contains numbers in Python?
I have a variable which I am convert to float, but I want to make if statement, to convert it to float only if it contains only numbers.
Just convert it and catch the exception if it fails.
s = "3.14"
try:
val = float(s)
except ValueError:
val = None
math.isnan(s).math.isinf. While not numbers, all three are valid floats, so whether to include them or not will probably depend on the intended usage of those floats.I would use a try-except block to determine if it is a number. That way if s is a number the cast is successful, and if it isn't you catch the ValueError so your program doesn't break.
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
You could also extract numbers from a string.
import string
extract_digits = lambda x: "".join(char for char in x if char in string.digits + ".")
and then convert them to float.
to_float = lambda x: float(x) if x.count(".") <= 1 else None
>>> token = "My pants got 2.5 legs"
>>> extract_digits(token)
'2.5'
>>> to_float(_)
2.5
>>> token = "this is not a valid number: 2.5.52"
>>> extract_digits(token)
'2.5.52'
>>> to_float(_)
None
Michael Barber's answer will be best for speed since there's no unnecessary logic. If for some reason you find you need to make a more granular assessment, you could use the Python standard library's regular expression module. This would help you if you decided, for example, that you wanted to get a number like you described but had additional criteria you wanted to layer on.
import re
mystring = '.0323asdffa'
def find_number_with_or_without_decimal(mystring):
return re.findall(r"^\.?\d+", mystring)
In [1]: find_number_with_or_without_decimal(mystring)
Out[1]: ['.0323']
The regular expression says, 'find something that starts with up to one decimal ('^' means only at beginning of line and the '?' means up to one; the decimal is escaped with a '\' so it won't have its special regular expression meaning of 'any character') and has any number of digits. Good luck with Python!