0

I have been working with some Python imaging libraries lately and i have been getting issues extracting the text from the last three lines of a string.

Lets say I have a string

a = '''
Human
Dog
Cat
Banana
Apple
Orange'''

And i want to convert the stuff into 2 different lists, one of which has the last three lines of the string, the other of which has all the rest of the lines of the string.

first_items = ['Human', 'Dog', 'Cat']
last_items = ['Banana', 'Apple', 'Orange']

How do I do this in Python?

Zags
  • 37,389
  • 14
  • 105
  • 140
DankCoder
  • 369
  • 1
  • 4
  • 15

3 Answers3

3

First, you need your data by line, filtering out empty lines:

lines = list(filter(None, a.splitlines()))

Then, you can use Python's list slicing:

first = lines[:-3]
last = lines[-3:]
Zags
  • 37,389
  • 14
  • 105
  • 140
  • well what if there is a gap between the last 3 lines, it just pushes the gap into the list as well. Any solutions to that? – DankCoder Dec 13 '18 at 15:34
  • @GoodBoye I've updated the solution to filter out any empty lines – Zags Dec 13 '18 at 15:36
  • TypeError: 'filter' object is not subscriptable – DankCoder Dec 13 '18 at 15:40
  • i dont have any functions or variables assigned for filter. Is it because i am using python 3.6? – DankCoder Dec 13 '18 at 15:44
  • @GoodBoye Ah, it's a Python 3 thing. Example updated – Zags Dec 13 '18 at 15:45
  • Wouldn't be simpler to just use [`str.splitlines()`](https://docs.python.org/3/library/stdtypes.html#str.splitlines)? i.e. `lines = a.splitlines()` – martineau Dec 13 '18 at 16:03
  • @martineau Simpler? No. More robust? Yes. `splitlines` does not filter out empty lines; it just catches more newline characters – Zags Dec 13 '18 at 16:05
  • No need for the `list()` (and probably the `filter()`), if you read the documentation you would see it returns one. – martineau Dec 13 '18 at 16:06
  • @martineau casting to a list is needed because `filter` returns an iterator in Python 3 – Zags Dec 13 '18 at 16:07
  • The OP said nothing about filtering or blank lines—so you don't need to use it. It would probably be better to just use a list comprehension even if it was needed. – martineau Dec 13 '18 at 16:08
0
a = '''Human
Dog
Cat
Banana
Apple
Orange'''

full_list = a.split('\n')

list1 = full_list[:-3]
last_items = full_list[-3:]

Output:

In [6]: list1
Out[6]: ['Human', 'Dog', 'Cat']

In [7]: last_items
Out[7]: ['Banana', 'Apple', 'Orange']
chitown88
  • 27,527
  • 4
  • 30
  • 59
0
a = '''
Human
Dog
Cat
Banana
Apple
Orange'''

a here is a string, so we should convert it into a list by splitting it with new-line character \n, and trim the leading \n by taking list from 1st item instead of 0th item

full_list = a.split('\n')[1:]

it will give ['Human', 'Dog', 'Cat', 'Banana', 'Apple', 'Orange']

Now top three can be extracted with [:-3] and last three with [-3:]

list1 = full_list[:3]  
last_items = full_list[-3:]

Hope it helps.

sid8491
  • 6,622
  • 6
  • 38
  • 64