Python不忽略lis中的空项

2024-09-29 23:22:58 发布

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

我有这段代码可以将一些字符串打印到文本文件中,但我需要python忽略每个空项,这样它就不会打印空行。
我写了这段代码,很简单,但应该做到:

lastReadCategories = open('c:/digitalLibrary/' + connectedUser + '/lastReadCategories.txt', 'w')
for category in lastReadCategoriesList:
    if category.split(",")[0] is not "" and category is not None:
        lastReadCategories.write(category + '\n')
        print(category)
    else: print("/" + category + "/")
lastReadCategories.close()

我看不出有什么问题,但是python一直在将空项打印到文件中。所有类别都是用这样的符号编写的:“category,timeread”,这就是为什么我要求python查看逗号前的第一个字符串是否不是空的。然后我看看整个项目是否不是空的(不是没有)。理论上我想应该行得通,对吧?
P、 S:我已经试过询问if来检查“category”是否不是“and not”,结果还是一样的。在


Tags: and字符串代码ifisnotopenprint
3条回答

rstrip()在将类别写回文件之前

lastReadCategories = open('c:/digitalLibrary/' + connectedUser +'/lastReadCategories.txt', 'w')
for category in lastReadCategoriesList:
if category.split(",")[0] is not "" and category is not None:
    lastReadCategories.write(category.rstrip() + '\n')
    print(category.rstrip())
else: print("/" + category + "/")
lastReadCategories.close()

我可以用您提供的样本列表测试它(无需将其写入文件):

^{pr2}$

测试空字符串(即只使用空格而不是'')的经典方法是使用str.strip()

>>> st='   '
>>> bool(st)
True
>>> bool(st.strip())
False

它也适用于空字符串:

^{pr2}$

您有if category.split(",")[0] is not "" ...,这不是推荐的方法。您可以这样做:

if category.split(',')[0] and ...

或者,如果你想说得更详细些:

if bool(category.split(',')[0]) is not False and ...

您可能正在处理CSV中前导空格的问题:

>>> '    ,'.split(',')
['    ', '']
>>> '     ,val'.split(',')
['     ', 'val'] 

请改为测试布尔真值,并反转测试,以便您确定.split()将首先工作,None.split()将引发异常:

if category is not None and category.split(",")[0]:

空字符串是'false-y',没有必要对它进行任何测试。在

你甚至可以测试一下:

^{pr2}$

为了同样的结果。在

从评论来看,你的数据中似乎出现了新行。测试时请将其剥离:

for category in lastReadCategoriesList:
    category = category.rstrip('\n')
    if category and not category.startswith(','):
        lastReadCategories.write(category + '\n')
        print(category)
    else: print("/{}/".format(category))

请注意,您可以在循环中简单地修改category;这避免了多次调用.rstrip()。在

相关问题 更多 >

    热门问题