get nth line of string in python

后端 未结 9 1815
萌比男神i
萌比男神i 2021-01-02 08:50

How can you get the nth line of a string in Python 3? For example

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

Is there any way to do this

9条回答
  •  庸人自扰
    2021-01-02 09:33

    A more efficient solution than splitting the string would be to iterate over its characters, finding the positions of the Nth and the (N - 1)th occurence of '\n' (taking into account the edge case at the start of the string). The Nth line is the substring between those positions.

    Here's a messy piece of code to demonstrate it (line number is 1 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
    

    This is also more efficient than the solution which builds up the string one character at a time.

提交回复
热议问题