首页 > 解决方案 > 无法删除列表中的“某些”空项目

问题描述

我已经编码了一段时间,但最近我遇到了一个矛盾的问题。出于某种原因,在打印的“第三阶段”中,列表中仍有空项目。这很奇怪,因为代码的一部分应该删除所有为空的项目,但仍然有一些。. . .

我发现的唯一问题是包含两个逗号连接的字符串 " ,," 并且中间逗号不会被删除。

不幸的是,我无法解决这个问题,也没有找到任何可以帮助我解决问题的方法。预先感谢您提供的任何帮助!

SpecificPlayerChat = "!get specific player chat log:  ,   ,, ,,, username | category"
#Removing all spaces found within the string
SpecificPlayerChat = SpecificPlayerChat.replace(" ","").strip().replace("\n","")
print("First Stage:", SpecificPlayerChat)

#Store the string username & category data only and split the rest into a "junk" string
junk,SpecificPlayerChatData = SpecificPlayerChat.split(":")
print("Second Stage:", SpecificPlayerChatData)
junk = "" #This string deleted the unwanted string

#Split the usernames and categories into two separate strings
usernames,categories = SpecificPlayerChatData.split("|")
print("Third Stage:", usernames)

#Split the multiple words or "no words" into an item each to be store in a list
usernamelist = []
categorylist = []
usernamelist = usernames.split(",")
categorylist = categories.split(",")

#remove any empty items
print("   Print Empty items:")
for item in usernamelist:
    if item is '':
        usernamelist.remove(item)
        print("     Empty Item Detected!")
print("Third Stage ", usernamelist)

标签: pythonstringlistreplaceelement

解决方案


这个打印显示了吗?

print("     Empty Item Detected!")

试试这个而不是删除:

将其替换为:

for item in usernamelist:
if item is '' or item is null:
    usernamelist.remove(item)
    print("     Empty Item Detected!")

有了这个:

for item in usernamelist:
if item is '' or item is null:
    del usernamelist[usernamelist.index(item)]
    print("     Empty Item Detected!")

参考: https : //www.w3schools.com/python/ref_keyword_del.asp,https: //www.programiz.com/python-programming/methods/list/index


推荐阅读