【问题标题】:Python find index of string with while loopPython使用while循环查找字符串索引
【发布时间】:2021-12-19 22:02:11
【问题描述】:

python新手-

我需要创建一个“while”循环来搜索某个字符串在文本文件中的位置。

文件中的所有字符都已设置为整数 (x = len(all)),所以现在我需要一个循环来搜索某个字符串的索引/位置。

这就是我现在所处的位置:

string = 'found' 
index = 0 

while index < x:
   if ????

然后它应该打印出类似的东西

String found between (startIndex) and (endIndex)

【问题讨论】:

  • 请提供输入文件的示例和匹配的预期输出。另外,这是作业吗?
  • 不是为了作业

标签: python loops parsing while-loop


【解决方案1】:

您可以使用 .find() 函数:

string = "found"
x = "I found the index"
index =  x.find(string)
end = index + len(string)
print(index, end)

2、7

【讨论】:

    【解决方案2】:

    Python 有一个名为 index 的内置函数,可提供此功能:

    string = "found"
    with open("FILE", "r") as f:
        for i,j in f.readlines():
            if string in j:
                foo = f.index(string)
                print(f"String found at line {i+1} between ({foo}) and ({foo + len(string)})")
                break
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-19
      • 1970-01-01
      • 1970-01-01
      • 2013-09-09
      • 2015-03-25
      • 2019-04-26
      • 2015-01-02
      • 2015-06-23
      相关资源
      最近更新 更多