[英]Remove blank string value from a list of strings
I am reading string information as input from a text file and placing them into lists, and one of the lines is like this: 我正在读取字符串信息作为文本文件的输入并将它们放入列表中,其中一行是这样的:
30121,long,Mehtab,10,20,,30
I want to remove the empty value in between the ,, portion from this list, but have had zero results. 我想删除此列表中的部分之间的空值,但结果为零。 I've tried .remove()
and filter()
. 我试过.remove()
和filter()
。 Python reads it as a 'str'
value. Python将其读作'str'
值。
>>> import re
>>> re.sub(',,+', ',', '30121,long,Mehtab,10,20,,30')
'30121,long,Mehtab,10,20,30'
Use split()
and remove()
使用split()
和remove()
In [11]: s = '30121,long,Mehtab,10,20,,30'
In [14]: l = s.split(',')
In [15]: l.remove('')
In [16]: l
Out[16]: ['30121', 'long', 'Mehtab', '10', '20', '30']
You can split the string based on your separator ("," for this) and then use list comprehension to consolidate the elements after making sure they are not blank. 您可以根据分隔符(“,”为此)拆分字符串,然后使用列表解析在确保元素不为空后合并元素。
",".join([element for element in string.split(",") if element])
We can also use element.strip()
as if condition if we want to filter out string with only spaces. 如果我们想要过滤掉只有空格的字符串,我们也可以使用element.strip()
作为条件。
Filter should work. 过滤器应该工作。 First I am writing the data in a list and then using filter operation to filter out items in a list which which are empty. 首先,我将数据写入列表,然后使用过滤器操作过滤列表中的项目,这些项目为空。 In other words, only taking items that are not empty. 换句话说,只采取非空的项目。
data = list("30121","long","Mehtab",10,20,"",30)
filtered_data = list(filter(lambda str: str != '', data))
print(filtered_data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.