Python: loop over a list of string and using split() -
i'm trying split elements of list:
text = ['james fennimore cooper\n', 'peter, paul, , mary\n', 'james gosling\n'] newlist = ['james', 'fennimore', 'cooper\n', 'peter', 'paul,', 'and', 'mary\n', 'james', 'gosling\n'] my code far is:
newlist = [] item in text: newlist.extend(item.split()) return newlist and error:
builtins.attributeerror: 'list' object has no attribute 'split'
don't use split() here it'll strip trailing '\n', use split(' ').
>>> text = ['james fennimore cooper\n', 'peter, paul, , mary\n', ... 'james gosling\n'] >>> [y x in text y in x.split(' ')] ['james', 'fennimore', 'cooper\n', 'peter,', 'paul,', 'and', 'mary\n', 'james', 'gosling\n'] and in case number of spaces not consistent may have use regex:
import re [y x in text y in re.split(r' +', x)]]
Comments
Post a Comment