Convert Multiline into list
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'
精彩评论