首页 > 解决方案 > 查找包含给定跨度的行号

问题描述

给定一个文本文件,如何找到与给定子字符串的开始和结束索引对应的行号?即使可以找到任何给定跨度的值,我正在使用的数据集也包含重复项。

标签: pythonfileindices

解决方案


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

我猜 ...

my_string = """
hello
test
line 
numbers
"""

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

推荐阅读