[英]Check if string is float expressed as a decimal number only
I'm writing script for checking if a pair of numbers is a valid coordinate. 我正在编写用于检查一对数字是否为有效坐标的脚本。 I need to check if the numbers are expressed as decimals only and in the range of 0 to 180 positive or negative for longitude and 0 to 90 positive or negative for latitude. 我需要检查数字是否仅用小数表示,经度的范围是0到180正或负,纬度的范围是0到90正或负。 I have used a try/except block to check if the number is a float like this: 我使用了try / except块来检查数字是否像这样的浮点数:
def isFloat(n):
try:
float(n)
return True
except ValueError:
return False
While this mostly works, I want it to accept floats expressed only as decimals and not values like True
, False
, 1e1
, NaN
尽管这大部分有效,但我希望它接受仅以小数表示的浮点数,而不接受True
, False
, 1e1
, NaN
You could use a fairly simple regular expression : 您可以使用一个相当简单的正则表达式 :
import re
def isFloat(n):
n = str(n) # optional; make sure you have string
return bool(re.match(r'^-?\d+(\.\d+)?$', n)) # bool is not strictly necessary
# ^ string beginning
# -? an optional -
# \d+ followed by one or more digits (\d* if you want to allow e.g. '.95')
# (\.\d+)? followed by an optional group of a dot and one or more digits
# $ string end
>>> isFloat('4')
True
>>> isFloat('4.567')
True
>>> isFloat('-4.567')
True
>>> isFloat('-4.')
False
>>> isFloat('-4.45v')
False
>>> isFloat('NaN')
False
>>> isFloat('1e1')
False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.