Python有没有办法检测值是否为空?

2024-06-02 04:54:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一段代码,它将获取字符串中的某些值并输出它们。问题是我使用的数据集并不完美,而且有许多部分的数据是空的。我正在寻找一种方法,让Python忽略空白值,然后继续前进

rfile = open("1.txt", "r", encoding= "utf8")
combos = rfile.readlines()
a=0
nfile = open("2.txt ", "w+")

numx = 0

for line in combos:
    x = combos[a]
    y=(x.split('Points = '))
    z= int(y[-1])
    numx += 1
    print (z)

print (numx)
rfile.close()
nfile.close()
exi = input("Press any key to close")

数据集的示例如下所示:

Person 1 | Points = 22 
Person 2 | Points =     <--- This is the problematic data 
Person 3 | Points = 15

任何帮助都将不胜感激


Tags: 数据方法字符串代码txtcloseopen空白
2条回答

之后

    y = (x.split('Points = '))

如果保证缺少数据的行在=之后只有一个空格,例如'Person 2 | Points = ',这样y[-1] == '',您只需执行以下操作即可跳过该行并继续(转到for循环的下一次迭代的开始):

    if not y:
        continue

依赖于一个空字符串计为假值这一事实

如果它可能包含额外的空格,那么您必须处理这个问题。有多种选择:

  1. 逐个测试字符串的字符
    for c in y[-1]:   # looping over the characters in y[-1]
        if c != ' ':  # if a non-space character is found
            break     # then break from this inner "for" loop
    else:             # but if this loop completed without break
        continue      # then start next iteration of the outer "for" loop
  1. 使用正则表达式解析器(顶部需要import re
    if re.match('\s*$', y[-1]):
        continue
  1. 只要尝试将其转换为int,并在失败时捕获异常:
    try:
        z = int(y[-1])
    except ValueError:
        continue

(如果字符串确实为空,所有这些操作仍然有效。)

您可以检查变量是否为空字符串,或者是否为无,例如: if not value: continue

相关问题 更多 >