0

I have a big txt file and I want to split it into a list where every word is a element of the list. I want to commas to be included on the elements like the example.

txt file Hi, my name is Mick and I want to split this with commas included, like this. list ['Hi,','my','name','is','Mick' etc. ]

Thank you very much for the help

  • Does this answer your question? [In Python, how do I split a string and keep the separators?](https://stackoverflow.com/questions/2136556/in-python-how-do-i-split-a-string-and-keep-the-separators) – azro Feb 28 '21 at 18:43
  • You may think about [accepting an answer](https://stackoverflow.com/help/someone-answers) to reward those how helped you, or at least comment to explain what's missing ;) – azro Mar 27 '21 at 11:42

1 Answers1

4

Just use str.split() without any pattern, it'll split on space(s)

value = 'Hi, my name is Mick and I want to split this with commas included, like this.'
res = value.split()
print(res) # ['Hi,', 'my', 'name', 'is', 'Mick', 'and', 'I', 'want', 'to', 'split', 'this', 'with', 'commas', 'included,', 'like', 'this.']

res = [r for r in value.split() if ',' not in r]
print(res) # ['my', 'name', 'is', 'Mick', 'and', 'I', 'want', 'to', 'split', 'this', 'with', 'commas', 'like', 'this.']
azro
  • 53,056
  • 7
  • 34
  • 70