这篇文章已经有很好的回答了。我想提供一种略微不同的观点。
我们可以进行字母的负面搜索,而不是寻找数字或浮点数。也就是说,我们可以让程序查找它是否不是字母。
print(not "-1.2345".isalpha())
print(not "-1.2345e-10".isalpha())
如果您确定字符串是格式良好的数字(如下面的条件1和条件2),它将有效地工作。但是,如果字符串不是一个格式良好的数字,那么它将失败。在这种情况下,它将返回一个数字匹配,即使该字符串不是一个有效的数字。为了处理这种情况,必须有许多基于规则的方法。然而,此时此刻,正则表达式浮现在我的脑海中。以下是三种情况。请注意,由于我不是正则表达式专家,因此正则表达式可能会更好。下面有两个列表:一个是有效数字,另一个是无效数字。必须选择有效数字,而无效数字则不得选取。
== 条件1:字符串保证是有效数字,但不包括'inf' ==
Valid_Numbers = ["1","-1","+1","0.0",".1","1.2345","-1.2345","+1.2345","1.2345e10","1.2345e-10","-1.2345e10","-1.2345E10","-inf"]
Invalid_Numbers = ["1.1.1","++1","--1","-1-1","1.23e10e5","--inf"]
Case_1_Positive_Result = list(map(lambda x: not x.isalpha(),Valid_Numbers))
print("The below must all be True")
print(Case_1_Positive_Result)
Case_1_Negative_Result = list(map(lambda x: not x.isalpha(),Invalid_Numbers))
print("The below must all be False")
print(Case_1_Negative_Result)
The below must all be True
[True, True, True, True, True, True, True, True, True, True, True, True, True]
The below must all be False
[True, True, True, True, True, True]
== 条件2: 字符串保证是一个有效的数字,且选取 'inf' ==
Case_2_Positive_Result = list(map(lambda x: x=="inf" or not x.isalpha(),Valid_Numbers+["inf"]))
print("The below must all be True")
print(Case_2_Positive_Result)
Case_2_Negative_Result = list(map(lambda x: x=="inf" or not x.isalpha(),Invalid_Numbers+["++inf"]))
print("The below must all be False")
print(Case_2_Negative_Result)
The below must all be True
[True, True, True, True, True, True, True, True, True, True, True, True, True, True]
The below must all be False
[True, True, True, True, True, True, True]
== 条件3:字符串不保证是有效的数字 ==
import re
CompiledPattern = re.compile(r"([+-]?(inf){1}$)|([+-]?[0-9]*\.?[0-9]*$)|([+-]?[0-9]*\.?[0-9]*[eE]{1}[+-]?[0-9]*$)")
Case_3_Positive_Result = list(map(lambda x: True if CompiledPattern.match(x) else False,Valid_Numbers+["inf"]))
print("The below must all be True")
print(Case_3_Positive_Result)
Case_3_Negative_Result = list(map(lambda x: True if CompiledPattern.match(x) else False,Invalid_Numbers+["++inf"]))
print("The below must all be False")
print(Case_3_Negative_Result)
The below must all be True
[True, True, True, True, True, True, True, True, True, True, True, True, True, True]
The below must all be False
[False, False, False, False, False, False, False]
x = float('0.00'); if x: use_float(x);
,你的代码中现在有一个bug。这些函数抛出异常而不是一开始返回None
的原因是为了避免Truthy值。更好的解决方案是在需要使用时避免实用程序函数,而是在调用float时使用try catch语句块捕获异常。 - ovangle