我希望找到在python中测试字符串是否通过以下条件的最有效和最简单的方法:
我可以很容易地使用嵌套的' if‘循环,等等,但我想知道是否有更方便的方法.
例如,我想要字符串:
0.0009017041601 5.13623e-05 0.00137531 0.00124203为“真”,以下为“假”:
# File generated at 10:45am Tuesday, July 8th
# Velocity: 82.568
# Ambient Pressure: 150000.0
Time(seconds) Force_x Force_y Force_z发布于 2014-12-04 10:05:05
这对于正则表达式来说很简单,使用字符类
import re
if re.match(r"[0-9e \t+.-]*$", subject):
# Match!然而,这将(根据规则)也匹配eeeee或+-e-+等.
如果您实际要做的是检查给定的字符串是否为有效数字,则只需使用
try:
num = float(subject)
except ValueError:
print("Illegal value")这将处理像"+34"、"-4e-50"或" 3.456e7 "这样的字符串。
发布于 2014-12-04 10:04:17
import re
if re.match(r"^[0-9\te+ -]+$",x):
print "yes"
else:
print "no"您可以尝试this.If,有一个匹配,它是一个传递,否则fail.Here x将是您的字符串。
发布于 2014-12-04 10:09:46
您不需要使用正则表达式,只需使用test_list和all操作:
>>> from string import digits
>>> test_list=list(digits)+['+','-',' ','\t','e','.']
>>> all(i in test_list for i in s)演示:
>>> s ='+4534e '
>>> all(i in test_list for i in s)
True
>>> s='+9328a '
>>> all(i in test_list for i in s)
False
>>> s="0.0009017041601 5.13623e-05 0.00137531 0.00124203"
>>> all(i in test_list for i in s)
Truehttps://stackoverflow.com/questions/27291079
复制相似问题