Check string for numbers in Python

How to check if a string contains numbers in Python?

I have a variable that I convert to float, but I want to make an if statement to convert it to float only if it contains only numbers.

+4
source share
5 answers

Just convert it and catch the exception if it fails.

s = "3.14" try: val = float(s) except ValueError: val = None 
+9
source

I would use a try-except block to determine if this is a number. Thus, if s is a number, then the cast is successful, and if you do not catch a ValueError, then your program will not break.

 def is_number(s): try: float(s) return True except ValueError: return False 
+3
source

You can 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 
+2
source

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

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

When looking at error handling in Python, I believe that it was Master Yoda who said, "There is no attempt to do or not to do."

+2
source

Michael Barber's answer will be better for speed, as there is no unnecessary logic. If for some reason you find that you need a more detailed evaluation, you can use the standard regex module of the Python standard library. This will help you if, for example, you decide that you want to get the number as you described, but with additional criteria that you want to overlay.

 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 starting with one decimal place (" ^ "means only at the beginning of the line, and"? "Means up to one, decimal escapes with" \ "so that it won 'has its own special meaning of regular expression "any character") and has any number of digits. Good luck with Python!

+1
source

All Articles