-1

I have string value:

    str1 = """
          first line
          second line
          abc
          def
          xyz
          123
          lastline"""

How to skip first two lines and last line and print remaining lines.

Code: I tried and works for to skip first two lines

for index, line in enumerate(str1.split("\n")):
    if index <= 1:
        continue
    print line

Output getting from above code:

          abc
          def
          xyz
          123
          lastline

Expected output:

          abc
          def
          xyz
          123
CristiFati
  • 38,250
  • 9
  • 50
  • 87
Sagar
  • 59
  • 4
  • 11

1 Answers1

2

Use string.splitlines():

>>> str1.splitlines()[3:-1]
['          abc', '          def', '          xyz', '          123']

Note that the first line (index 0) is empty. It is terminated by the first \n directly after the opening double quotes.

  • 1
    I think that should be `[2:-1]`. – John Gordon Apr 09 '18 at 18:43
  • Actually it is `[3:-1]` because of the leading `\n`. –  Apr 09 '18 at 18:44
  • I am end up with using [3: -2] because I have last line is empty line. Shall i use filter to remove empty lines from the list? – Sagar Apr 09 '18 at 18:57
  • That depends on your requirements. If you know the number of lines, even the empty ones, the slice approach should work fine. But if you want to remove empty lines somewhere in the file, filter them. –  Apr 09 '18 at 18:59