开发者

Check string for numbers in Python

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


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


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."


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜