Get nth line of string in python

How can you get the nth line of a line in Python 3? for instance

getline("line1\nline2\nline3",3) 

Is there a way to do this using the stdlib / builtin functions? I prefer the solution in Python 3, but Python 2 is fine too.

+4
source share
7 answers

Try the following:

 s = "line1\nline2\nline3" print s.splitlines()[2] 
+14
source

functional approach

 >>> import StringIO >>> from itertools import islice >>> s = "line1\nline2\nline3" >>> gen = StringIO.StringIO(s) >>> print next(islice(gen, 2, 3)) line3 
+3
source

Use a string buffer:

 import io def getLine(data, line_no): buffer = io.StringIO(data) for i in range(line_no - 1): try: next(buffer) except StopIteration: return '' #Reached EOF try: return next(buffer) except StopIteration: return '' #Reached EOF 
+2
source

From the comments it seems that this line is very large. If there is too much data to fit into memory conveniently, one approach is to process the data from the file line by line as follows:

 N = ... with open('data.txt') as inf: for count, line in enumerate(inf, 1): if count == N: #search for the N'th line print line 

Using enumerate () gives you the index and value of the object you are iterating over and you can specify the starting value, so I used 1 (instead of the default value of 0)

The advantage of using with is that it automatically closes the file for you when you are finished, or if you encounter an exception.

+1
source

Since you have improved memory efficiency, this is better:

 s = "line1\nline2\nline3" # number of the line you want line_number = 2 i = 0 line = '' for c in s: if i > line_number: break else: if i == line_number-1 and c != '\n': line += c elif c == '\n': i += 1 
+1
source

A more effective solution than splitting a string would be to iterate over its characters, find the positions of the Nth and (N - 1) -th appearance of "\ n" (taking into account the edge case at the beginning of the String). The nth line is a substring between these positions.

Here's a messy piece of code to demonstrate it (line number 1 is indexed):

 def getLine(data, line_no): n = 0 lastPos = -1 for i in range(0, len(data) - 1): if data[i] == "\n": n = n + 1 if n == line_no: return data[lastPos + 1:i] else: lastPos = i; if(n == line_no - 1): return data[lastPos + 1:] return "" # end of string 

It is also more efficient than a solution that creates a string one character at a time.

0
source

My solution (efficient and compact):

 def getLine(data, line_no): index = -1 for _ in range(line_no):index = data.index('\n',index+1) return data[index+1:data.index('\n',index+1)] 
-1
source

All Articles