且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-02 23:36:04

请不要在此处使用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)]]