7

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.

2
  • One more thing, the number in variable is like "0.123" Commented Aug 4, 2011 at 13:07
  • That is still valid for conversion to a float Commented Aug 4, 2011 at 13:10

5 Answers 5

10

Just convert it and catch the exception if it fails.

s = "3.14"
try:
  val = float(s)
except ValueError:
  val = None
Sign up to request clarification or add additional context in comments.

4 Comments

I think this is fastest approach.
This let's "NaN" (Not a Number) through. To explicitly check for those use math.isnan(s).
@razz0 makes a good point. This approach also allows "inf" and "-inf" through, which aren't numbers either; these can be checked with 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.
how do you do this inside a filter() function with a lambda?
3

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

1 Comment

Since you explained the most, your answer is better! Thank you both, Michael and Hunter!
2

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

Comments

2

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!

Comments

2

Why not the built-in .isdigit() for this. Compact, no try statements, and super fast:

string = float(string) if string.isdigit() else string

When considering error handling in Python, I believe it was Master Yoda who said, "There is no try. Do or do not."

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.