nagymusic
nagymusic

Reputation: 71

Split a Python string (sentence) with appended white spaces

Might it be possible to split a Python string (sentence) so it retains the whitespaces between words in the output, but within a split substring by appending it after each word?

For example:

given_string = 'This is my string!'
output = ['This ', 'is ', 'my ', 'string!']

Upvotes: 1

Views: 258

Answers (3)

erhesto
erhesto

Reputation: 1186

I avoid regexes most of the time, but here it makes it really simple:

import re

given_string = 'This is my string!'
res = re.findall(r'\w+\W?', given_string)

# res ['This ', 'is ', 'my ', 'string!']

Upvotes: 5

Glyphack
Glyphack

Reputation: 886

just split and add the whitespace back:

a = " "
output =  [e+a for e in given_string.split(a) if e]
output[len(output)-1] = output[len(output)-1][:-1]

the last line is for deleting space after thankyou!

Upvotes: 0

Diman
Diman

Reputation: 418

Maybe this will help?

>>> given_string = 'This is my string!'
>>> l = given_string.split(' ')
>>> l = [item + ' ' for item in l[:-1]] + l[-1:]
>>> l
['This ', 'is ', 'my ', 'string!']

Upvotes: 0

Related Questions