【问题标题】:Is there a way for Python to detect whether a value is empty?Python有没有办法检测一个值是否为空?
【发布时间】:2020-06-21 20:08:45
【问题描述】:

我正在尝试编写一段代码,它将获取字符串中的某些值并输出它们。问题是我正在使用的数据集并不完美,并且有很多部分数据是空的。我正在寻找一种方法让 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

任何帮助将不胜感激!

【问题讨论】:

  • 澄清一下,我想让python检查z是否为空,如果是就忽略它。
  • if z: 应该可以工作。
  • 你可以检查y[-1]是否为空字符串""
  • 这能回答你的问题吗? python: how to check if a line is an empty line
  • z= y[-1] != ''? int(y[-1]) : ''

标签: python arrays


【解决方案1】:

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

【讨论】:

    【解决方案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
    

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

    【讨论】:

      猜你喜欢
      • 2021-08-10
      • 2014-12-15
      • 2014-04-05
      • 2011-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-01
      相关资源
      最近更新 更多