-1

I am trying to split a string, but keep all separators bundled together in a separate list.

s = "This is a test     for \n a string"

should results in

a = ["This", "is", "a", "test", "for", "a", "string"]
b = [" ", " ", " ", "     ", " \n ", " "]

Any idea on how to handle that?

cs95
  • 379,657
  • 97
  • 704
  • 746
fsociety
  • 1,791
  • 4
  • 22
  • 32
  • 2
    Downvoters, it isn't _that_ bad a question. The problem statement is clear and the question is answerable. – cs95 May 29 '18 at 09:14
  • How do you define *separators*? Is it everything that is not a word? How would the result look like if your text string ended with `.`? – Ma0 May 29 '18 at 09:16
  • 1
    Possibly duplicate https://stackoverflow.com/questions/2136556/in-python-how-do-i-split-a-string-and-keep-the-separators/34004805?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Mazdak May 29 '18 at 09:17

1 Answers1

4

re.split is your friend:

split = re.split(r'(\s+)', s)   
x = split[::2]
y = split[1::2]

>>> x
['This', 'is', 'a', 'test', 'for', 'a', 'string']
>>> y
[' ', ' ', ' ', '     ', ' \n ', ' ']
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
cs95
  • 379,657
  • 97
  • 704
  • 746