如何检查字符串是否为空或长度为零

3 投票
4 回答
15195 浏览
提问于 2025-04-16 14:39

我最近问了一个问题,关于如何把文本文件里的值转换成字典列表。你可以通过这个链接查看我的问题:查看我的问题


P883, Michael Smith, 1991
L672, Jane Collins, 1992

(added)
(empty line here)
L322, Randy Green, 1992
H732, Justin Wood, 1995(/added)
^key ^name ^year of birth

===============
这个问题已经有人回答了,我用的是下面这段代码(被接受的答案),效果很好:

def load(filename): students = {}

   infile = open(filename)
   for line in infile:
       line = line.strip()
       parts = [p.strip() for p in line.split(",")]
       students[parts[0]] = (parts[1], parts[2])
   return students 


不过,当文本文件里的值中有空行的时候……(见添加的部分),代码就不再有效了,出现了一个错误,提示说列表索引超出范围。

4 个回答

0
lines = [line.split(', ') for line in file if line]
result = dict([(list[0], element_list[1:]) for line in lines if line])

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

0

检查一行是否为空或者长度为0其实非常简单:

for line in infile:
    line = line.strip()
    if line:
       do_something()

    # or

    if len(line) > 0:
        do_something()
7

在你的循环里面检查一下有没有空行,如果有的话就跳过这些空行:

for line in infile:
    line = line.strip()
    if not line:
        continue
    parts = [p.strip() for p in line.split(",")]
    students[parts[0]] = (parts[1], parts[2])

撰写回答