我正在尝试拆分列表的元素:
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']
到目前为止我的代码是:
newlist = []
for item in text:
newlist.extend(item.split())
return newlist
我收到错误:
builtins.AttributeError: 'list' object has no attribute 'split'
答案 0 :(得分:4)
请勿在此使用split()
,因为它还会删除尾随'\n'
,使用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']
如果空格数不一致,则可能必须使用正则表达式:
import re
[y for x in text for y in re.split(r' +', x)]]
答案 1 :(得分:1)
基于@Aशwiniचhaudhary的回复,如果你有兴趣从你的字符串片段中删除尾随的,
和\n
,你可以做到
[y.rstrip(',\n') for x in text for y in x.split(' ')]