2

I'm trying to split the elements of a list:

text = ['James Fennimore Cooper\n', 'Peter, Paul, and Mary\n',
        'James Gosling\n']

newlist = ['James', 'Fennimore', 'Cooper\n', 'Peter', 'Paul,', 'and', 'Mary\n',
        'James', 'Gosling\n']

My code so far is:

newlist = []

for item in text:
    newlist.extend(item.split())

return newlist

And I get the error:

builtins.AttributeError: 'list' object has no attribute 'split'

wflynny
  • 18,065
  • 5
  • 46
  • 67
user3402910
  • 21
  • 1
  • 1
  • 2

2 Answers2

5

Don't use split() here as it'll also strip the trailing '\n', use split(' ').

>>> text = ['James Fennimore Cooper\n', 'Peter, Paul, and Mary\n',
...         'James Gosling\n']
>>> [y for x in text for y in x.split(' ')]
['James', 'Fennimore', 'Cooper\n', 'Peter,', 'Paul,', 'and', 'Mary\n', 'James', 'Gosling\n']

And in case the number of spaces are not consistent then you may have to use regex:

import re
[y for x in text for y in re.split(r' +', x)]]
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
1

Building on @Aशwini चhaudhary's response, if you're interested in removing the trailing ,s and \ns from your string fragments, you could do

[y.rstrip(',\n') for x in text for y in x.split(' ')]
wflynny
  • 18,065
  • 5
  • 46
  • 67