我正在尝试拆分列表的元素:
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'
基于@Aशwiniचhaudhary的响应,如果您有兴趣从字符串片段中删除尾随的
,
s和\n
s,可以不要在这里使用
split()
,因为它还会去掉后面的'\n'
,使用split(' ')
。如果空格数不一致,则可能必须使用regex:
相关问题 更多 >
编程相关推荐