0

I have a list that consists of 149 text strings. From each string, I would like to extract the 2nd and 7th lines of text. I'd like the results of each line to be put in a separate list.

I've tried (just for one line):

text = []  
for string in list:
  x = string.splitlines()[2]
  text.append(x)

But I get the message "IndexError: list index out of range". I thought maybe I needed to do:

text = []  
for string in list:
  x = [string].splitlines()[2]
  text.append(x)

But that gave me the message "AttributeError: 'list' object has no attribute 'splitlines'"

I'm using Python 3.6. Any ideas? Thanks for your help!

4
  • 2
    You definitely didn't need to put it in brackets, that makes it a list. string.splitlines was correct, you just don't have 3 lines in that specific entry, apparently. (Without knowing what your data looks like, I can't say much more) Commented Jun 12, 2017 at 15:42
  • What is printed if you do print(len(string.splitlines())) right before assigning x in your first attempt? Commented Jun 12, 2017 at 16:12
  • Also, to extract the second line you should use string.splitlines()[1] - as 0 is the first element, 1 is the second and so on. Commented Jun 12, 2017 at 16:13
  • @JimFasarakisHilliard Thank you for the note about brackets. I didn't know that Commented Jun 12, 2017 at 16:52

1 Answer 1

2

string.splitlines is the correct function to split the lines of each string, and if it gives an IndexError for index 2 (note: this is the 3rd line) then that means that there are fewer than three lines. This is probably the code you're looking for:

line2_results = []
line7_results = []
for str in list:
    lines = str.splitlines()
    if len(lines) >= 2:
        line2_results.append(lines[1])
        if len(lines) >= 7:
            line7_results.append(lines[6])
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your help! Yes, there were blank strings in the input list and I see now that this was causing the error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.