Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Multiline into list

Tags:

python

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

like image 445
Sudeep Avatar asked Oct 03 '11 00:10

Sudeep


People also ask

How do you split a multiline string in Python?

Python String splitlines() method is used to split the lines at line boundaries. The function returns a list of lines in the string, including the line break(optional).

How do I split a string into multiple lines?

You can have a string split across multiple lines by enclosing it in triple quotes.


2 Answers

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']
like image 110
varunl Avatar answered Oct 29 '22 14:10

varunl


names.splitlines() should give you just that.

like image 25
wim Avatar answered Oct 29 '22 14:10

wim