Python:在字符串列表上循环并使用split()
我正在尝试拆分列表中的元素:Python:在字符串列表上循环并使用split(),python,string,list,loops,split,Python,String,List,Loops,Split,我正在尝试拆分列表中的元素: 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 it
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'对象没有属性“split”
不要在这里使用split()
,因为它还会剥离尾随的'\n'
,使用split('')
如果空格数不一致,则可能必须使用正则表达式:
import re
[y for x in text for y in re.split(r' +', x)]]
建立在@A之上श威尼चhaudhary的回答是,如果您有兴趣从字符串片段中删除尾随的
、
s和\n
s,您可以这样做
[y.rstrip(',\n') for x in text for y in x.split(' ')]
您发布的代码没有显示该错误。@mogambo
split
从不在text
上调用,而是在项上调用。
.Oops!你说得对。。。我的错。正在删除注释。可能与重复
[y.rstrip(',\n') for x in text for y in x.split(' ')]