get nth line of string in python

后端 未结 9 1837
萌比男神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:13

    My solution (effecient 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)]
    

提交回复
热议问题