Python - Deleting the first 2 lines of a string

前端 未结 6 1802
渐次进展
渐次进展 2021-02-07 00:39

I\'ve searched many threads here on removing the first two lines of a string but I can\'t seem to get it to work with every solution I\'ve tried.

Here is what my string

6条回答
  •  面向向阳花
    2021-02-07 01:32

    I'd rather not split strings in case the string is large, and to maintain newline types afterwards.

    Delete the first n lines:

    def find_nth(haystack, needle, n):
        start = haystack.find(needle)
        while start >= 0 and n > 1:
            start = haystack.find(needle, start+len(needle))
            n -= 1
        return start
    assert s[find_nth(s, '\n', 2) + 1:] == 'c\nd\n'
    

    See also: Find the nth occurrence of substring in a string

    Or to delete just one:

    s = 'a\nb\nc\nd\n'
    assert s[s.find('\n') + 1:] == 'b\nc\nd\n'
    

    Tested on Python 3.6.6.

提交回复
热议问题