Sudeep
Sudeep

Reputation: 513

Convert Multiline into list

I have extracted a set of data from HTML page and 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

Upvotes: 18

Views: 33123

Answers (3)

user
user

Reputation: 7333

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

Upvotes: -1

varunl
varunl

Reputation: 20229

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

Upvotes: 22

wim
wim

Reputation: 362557

names.splitlines() should give you just that.

Upvotes: 16

Related Questions