UnknoWn_UseR
UnknoWn_UseR

Reputation: 1

Is there a way to split strings inside a list?

I am trying to split strings inside a list but I could not find any solution on the internet. This is a sample, but it should help you guys understand my problem.

array=['a','b;','c','d)','void','plasma']
for i in array:
    print(i.split())

My desired output should look like this:

output: ['a','b',';','c','d',')','void','plasma']

Upvotes: 0

Views: 53

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521073

One approach uses re.findall on each starting list term along with a list comprehension to flatten the resulting 2D list:

inp = ['a', 'b;', 'c', 'd)', 'void', 'plasma']
output = [j for sub in [re.findall(r'\w+|\W+', x) for x in inp] for j in sub]
print(output)  # ['a', 'b', ';', 'c', 'd', ')', 'void', 'plasma']

Upvotes: 1

Related Questions