【发布时间】:2020-03-25 04:15:36
【问题描述】:
我已经编码了一段时间,但最近我遇到了一个相互矛盾的问题。出于某种原因,在打印的“第三阶段”中,列表中仍有空项目。这很奇怪,因为代码的一部分应该删除所有为空的项目,但有些仍然保留。 . . .
我发现唯一的问题是包含两个逗号的字符串连接“,,”和之间的不会被删除。
很遗憾,我无法解决这个问题,也没有找到任何可以帮助解决我的问题的方法。 提前感谢您提供的任何帮助!
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)
【问题讨论】:
-
你的
is null应该崩溃,因为它在 python 中是None。估计没有评价。我会调查一下。 -
ooh oops 在发布此内容时忘记将其删除!但是,是的,我不知道我在想什么,我只是累了。但是如果没有 null 部分,
if item is '':工作正常,但之后的操作不起作用。 -
尝试使用
usernamelist = [i for i in usernamelist if i](否则你的程序会崩溃,因为你正在迭代你试图从中删除项目的同一个列表)。如果您仍然有“空”项目并且您没有控制您的输入,我的猜测是您在这些字符串中有不可打印的字符 -
嗯,成功了!非常感谢!但如果你不介意,你能回答我
usernamelist = [i for i in usernamelist if i]的工作原理吗?谢谢! -
没问题,会做的!再次感谢!
标签: python string list replace element