开发者

Convert Multiline into list

开发者 https://www.devze.com 2023-04-09 20:58 出处:网络
I have extracted a set of data from HTML page an开发者_运维问答d copied to a variable. The variable looks like

I have extracted a set of data from HTML page an开发者_运维问答d copied to a variable. The variable looks like

names='''
      Apple
      Ball
      Cat'''

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


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


names.splitlines() should give you just that.


names.split('\n') should give you a list split by '\n'

0

精彩评论

暂无评论...
验证码 换一张
取 消