Python:循环遍历字符串列表并使用split() [英] Python: loop over a list of string and using split()

查看:557
本文介绍了Python:循环遍历字符串列表并使用split()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to split the elements of a list:

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']

到目前为止,我的代码是:

My code so far is:

newlist = []

for item in text:
    newlist.extend(item.split())

return newlist

我得到了错误:

builtins.AttributeError: 'list' object has no attribute 'split'

推荐答案

请不要在此处使用split(),因为它还会删除结尾的'\n',请使用split(' ').

Don't use split() here as it'll also strip the trailing '\n', use 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']

如果空格的数量不一致,那么您可能必须使用正则表达式:

And in case the number of spaces are not consistent then you may have to use regex:

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

这篇关于Python:循环遍历字符串列表并使用split()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆