merkle
merkle

Reputation: 1815

add a single spaces in list containing characters

I am new to the programming. I have a list. List contains multiple spaces. All the multiple spaces should be replaced with single space.

lis = ['h','e','l','l','','','','','o','','','','w']

output = ['h','e','l','l','','o','','w']

Could anyone tell how to do?

Upvotes: 2

Views: 148

Answers (5)

Andrej Kesely
Andrej Kesely

Reputation: 195543

Just simple list comprehension will suffice:

lis = ['h','e','l','l','','','','','o','','','','w']

output = [v for i, v in enumerate(lis) if v != '' or i == 0 or (v == '' and lis[i-1] != '')]
print(output)

This will print:

['h', 'e', 'l', 'l', '', 'o', '', 'w']

Upvotes: 1

rafaelc
rafaelc

Reputation: 59274

Why not just a for loop?

new_list = []
for char in lis:
    if char == '' and new_list[-1] == '': continue
    new_list.append(char)

Outputs

['h', 'e', 'l', 'l', '', 'o', '', 'w']

Upvotes: 0

Kasravnd
Kasravnd

Reputation: 107337

You can simply use zip() within a list comprehension as following:

In [21]: lis = ['', '', 'h','e','l','l','','','','','o','','','','w', '', '']

In [22]: lis[:1] + [j for i, j in zip(lis, lis[1:]) if i or j]
Out[22]: ['', 'h', 'e', 'l', 'l', '', 'o', '', 'w', '']

In this case we're looping over each pair an keeping the second item if one of the items in our pair is valid (not empty). You just then need to add the first item to the result because it's omitted.

Upvotes: 0

taras
taras

Reputation: 6915

You can use a list comprehension with enumerate and select only those '' which follow non-empty characters themselves

[c for i, c in enumerate(lis) if c or (not c and lis[i - 1])]

Upvotes: 0

jpp
jpp

Reputation: 164773

You can use itertools. The idea here is to group according whether strings are empty, noting bool('') == False.

from itertools import chain, groupby

L = (list(j) if i else [''] for i, j in groupby(lis, key=bool))

res = list(chain.from_iterable(L))

print(res)

['h', 'e', 'l', 'l', '', 'o', '', 'w']

Upvotes: 0

Related Questions