简体   繁体   中英

How to skip first two lines and last one line in python

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM