删除额外的空字符串?

时间:2018-05-31 14:34:58

标签: python string list

假设我有一个像这样的字符串的Python列表:

x = ["", "", "test", "", "", "not empty", "", "yes", ""]

如何删除:

  1. 所有领先的空字符串
  2. 所有尾随空字符串
  3. 所有'重复'空字符串
    (即将所有空空间值的内部序列减少为单个值)
  4. ['test', '', 'not empty', '', 'yes']

2 个答案:

答案 0 :(得分:0)

content = list(x.next() for i, x in it.groupby(content))
b_l_rgx = r"^(\s+)?$"
if re.match(b_l_rgx, content[0]):
    del content[0]
if len(content) > 0 and re.match(b_l_rgx, content[-1]):
    del content[-1]

答案 1 :(得分:0)

以下是我使用dropwhilegroupby

提出的解决方案
from itertools import groupby, dropwhile

def spaces(iterable):
    it = dropwhile(lambda x: not x, iterable)
    grby = groupby(it, key=bool)
    try:
        k, g = next(grby)
    except StopIteration:
        return
    yield from g
    for k, g in grby:
        if k:
            yield ''
            yield from g

x = ["", "", "test", "", "", "not empty", "", "yes", ""]
print(list(spaces(x)))
# ['test', '', 'not empty', '', 'yes']