python的新手-
我需要創建一個“while”回圈來搜索文本檔案中某個字串的位置。
檔案中的所有字符都已設定為整數(x = len(all)),所以現在我需要一個回圈來搜索某個字串的索引/位置。
這就是我現在所處的位置:
string = 'found'
index = 0
while index < x:
if ????
然后它應該列印出類似的東西
String found between (startIndex) and (endIndex)
uj5u.com熱心網友回復:
您可以使用 .find() 函式:
string = "found"
x = "I found the index"
index = x.find(string)
end = index len(string)
print(index, end)
2、7
uj5u.com熱心網友回復:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/351158.html
