get nth line of string in python

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

    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
    

提交回复
热议问题