Python - Deleting the first 2 lines of a string

前端 未结 6 1772
渐次进展
渐次进展 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:40

    You can find index of '\n' and ignore first; Then, start new string from end of second '\n' sub-string in main string.

    import re
    
    
    def find_sub_string_index(string, sub_string, offset=0, ignore=0):
        start = 0
        swap = len(sub_string)
        ignore += 1 # find first at least
        try:
            if start < 0:
                return -1 # Not Found
            if offset > 0:
                # Start main string from offset (offset is begining of check)
                string = string[offset:]
            for i in range(ignore):
                # swap: end of substring index
                # start is end of sub-string index in main string
                start += re.search(sub_string, string).start() + swap
                string = string[start:]
            return start
        except:
            return -1 # Got Error
    
    
    string = """The first line.
    The second line.
    The third line.
    The forth line.
    The fifth line."""
    sub_string = "\n"
    
    ignore = 1 # Ignore times
    
    start = find_sub_string_index(string, sub_string, ignore=1)
    
    print("Finding sub-string '{0}' from main text.".format(sub_string))
    print("Ignore {0} times.".format(ignore))
    print("Start index:", start)
    print("Result:")
    print(string[start:])
    

    The result is:

    $ python3 test.py
    Finding sub-string '
    ' from main text.
    Ignore 1 times.
    Start index: 33
    Result:
    The third line.
    The forth line.
    The fifth line.
    $
    $
    $
    $ python3 test.py
    Finding sub-string 'The' from main text.
    Ignore 2 times.
    Start index: 19
    Result:
     second line.
    The third line.
    The forth line.
    The fifth line.
    $
    

提交回复
热议问题