Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python how to get last N lines of a multiline string

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

like image 869
Bikesh M Avatar asked Oct 15 '25 22:10

Bikesh M


2 Answers

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'
like image 60
Błażej Michalik Avatar answered Oct 17 '25 11:10

Błażej Michalik


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.

like image 28
Kirill Artemenko Avatar answered Oct 17 '25 11:10

Kirill Artemenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!