get nth line of string in python

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

    Since you brought up the point of memory efficiency, is this any 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
    
    0 讨论(0)
  • 2021-01-02 09:12
    `my_string.strip().split("\n")[-1]`
    
    0 讨论(0)
  • 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)]
    
    0 讨论(0)
  • 2021-01-02 09:15

    Wrote into two functions for readability

        string = "foo\nbar\nbaz\nfubar\nsnafu\n"
    
        def iterlines(string):
          word = ""
          for letter in string:
            if letter == '\n':
              yield word
              word = ""
              continue
            word += letter
    
        def getline(string, line_number):
          for index, word in enumerate(iterlines(string),1):
            if index == line_number:
              #print(word)
              return word
    
        print(getline(string, 4))
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-02 09:27

    Try the following:

    s = "line1\nline2\nline3"
    print s.splitlines()[2]
    
    0 讨论(0)
提交回复
热议问题