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
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).
You can have a string split across multiple lines by enclosing it in triple quotes.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With