我已经编码了一段时间,但最近遇到了一个冲突的问题。由于某些原因,在打印的“第三阶段”中,列表中仍然有空项目。这很奇怪,因为代码的一部分应该删除所有为空的项目,但仍有一些保留。 。 。 。
我发现唯一的问题是包含两个逗号的字符串,它们之间连接了“ ,,
”和that,它们不会被删除。
不幸的是,我无法解决此问题,也找不到任何能帮助我解决当前情况的方法。预先感谢您提供的任何帮助!
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)
此图片显示吗?
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