Python:循环遍历字符串列表并使用split()

2024-05-29 11:07:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试拆分列表的元素:

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'


Tags: and代码text元素列表itempetersplit
2条回答

基于@Aशwiniचhaudhary的响应,如果您有兴趣从字符串片段中删除尾随的,s和\ns,可以

[y.rstrip(',\n') for x in text for y in x.split(' ')]

不要在这里使用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']

如果空格数不一致,则可能必须使用regex:

import re
[y for x in text for y in re.split(r' +', x)]]

相关问题 更多 >

    热门问题