将多行转换为列表 [英] Convert Multiline into list
本文介绍了将多行转换为列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经从HTML页面中提取了一组数据并复制到了一个变量中.变量看起来像
I have extracted a set of data from HTML page and copied to a variable. The variable looks like
names='''
Apple
Ball
Cat'''
现在,我想将每一行都加入一个列表,以便可以访问所需的任何行.有没有办法在Python中做到这一点
Now I like to join each line into a list so that I can access any line I want. Is there any way to do that in Python
推荐答案
使用splitlines()按换行符和strip()进行拆分,以删除不必要的空格.
Using splitlines() to split by newline character and strip() to remove unnecessary white spaces.
>>> names='''
... Apple
... Ball
... Cat'''
>>> names
'\n Apple\n Ball\n Cat'
>>> names_list = [y for y in (x.strip() for x in names.splitlines()) if y]
>>> # if x.strip() is used to remove empty lines
>>> names_list
['Apple', 'Ball', 'Cat']
这篇关于将多行转换为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文