Search code examples
pythonfileindices

Find the line number containing a given span


Given a text file, how would one find the line number corresponding to given start and end indices for a substring? Even though the value of any given span can be found, the data set I'm working with contains duplicates.


Solution

  • line_number = my_string[:start_index].count("\n")

    I guess ...

    my_string = """
    hello
    test
    line 
    numbers
    """
    
    print(my_string[:14].count("\n")) # the 14th character is the 3rd line