如何在python中启动循环之前比较字符串

时间:2014-11-30 22:10:52

标签: python loops python-3.x comparison

您好我从urllib.request.urlopen

中提取变量,称之为x

然后我想做一个浮动比较。

但是,由于此变量可能会有所变化且无法使用,因此偶尔会出现“N / A”

这是我的比较

    x = (sourceCode.split)('sourcesnippet1')[1].split('sourcesnippet2')[0]
    if 0 < float(x) < 1:
        print (entity, 'meets requirements')
        print (x)

我怎样才能使伪:

chek = 'N/A'
            x = (sourceCode.split)('sourcesnippet1')[1].split('sourcesnippet2')[0]
if str(x) == chek TRUE, then go to next query
else
            if 0 < float(x) < 1:
                print (entity, 'meets requirements')
                print (x)

1 个答案:

答案 0 :(得分:2)

根本不使用if,只需尝试将其转换为float,然后捕获异常:

parts = (sourceCode.split)('sourcesnippet1')
txt = parts[1].split('sourcesnippet2')[0]
try:
    x = float(txt)
except ValueError as err:
    print(err)
    continue
print ("Now I know, that I have a valid float...")
# do your stuff

这是Python中的流行风格,请参阅https://docs.python.org/2/glossary.html#term-eafp

您还可以防范其他错误,例如.split()仅返回一个元素:

parts = (sourceCode.split)('sourcesnippet1')
try:
    txt = parts[1].split('sourcesnippet2')[0]
    x = float(txt)
except (ValueError, LookupError) as err:
    print(err)
    continue