2

for example

mstr = """Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur laoreet
Suspendisse a erat mauris. Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
Praesent tempor dolor id tincidunt sagittis. 
Etiam eu massa in magna maximus gravida pulvinar in ante. 
Sed convallis venenatis risus. Mauris dapibus augue a arcu varius dignissim. 
Curabitur sapien odio, convallis non dictum eget, ornare quis urna. 
Ut cursus massa eget pellentesque varius"""

form the above string I need to get the last N lines in another variable

Is there any built n function available? or is there any effective ways to d this

Bikesh M
  • 8,163
  • 6
  • 40
  • 52
  • Does this answer your question? [Skip first couple of lines while reading lines in Python file](https://stackoverflow.com/questions/9578580/skip-first-couple-of-lines-while-reading-lines-in-python-file) – baduker Oct 07 '20 at 06:51

4 Answers4

7

str.splitlines() with a simple slice:

mstr.splitlines()[-n:]

The solution above will return these lines as a list. If you want a string, you also need to use str.join():

'\n'.join(mstr.splitlines()[-n:])

If your text doesn't contain it, you might also want to add the last newline, if you're catenating it with other text, or writing it to a file on UNIX-like OS:

'\n'.join(mstr.splitlines()[-n:]) + '\n'
Błażej Michalik
  • 4,474
  • 40
  • 55
2

To get the string value of the last N rows to another variable, use this:

new_mstr = "\n".join(mstr.splitlines()[-n:])

After getting the last N rows, you need to assemble it back into a string separated by newlines using join.

1

If you want to get the output in same format (that is multiline string) as input, just add join with the already provided answers.

'\n'.join(mstr.splitlines()[-n:]
soumya-kole
  • 1,111
  • 7
  • 18
0

This is the Best way to do that

os.linesep.join(str.split(os.linesep)[-n:])
AmirModiri
  • 755
  • 1
  • 5
  • 13