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'

4
  • 7
    The code you posted doesn't show that error. Commented Mar 10, 2014 at 18:04
  • @mogambo split is never called on text, but on item. Commented Mar 10, 2014 at 18:06
  • Oops! You're right... My bad. Deleting comment. Commented Mar 10, 2014 at 18:07
  • probably duplicate with stackoverflow.com/questions/6696027/… Commented Mar 10, 2014 at 18:15

2 Answers 2

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)]]
Sign up to request clarification or add additional context in comments.

Comments

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(' ')]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.