我正在逐行读取文件。我使用一个函数在一行中查找指定的字符。
def find_all(a_str, sub):
start = 0
while True:
start = a_str.find(sub, start)
if start == -1: return
yield start
start += len(sub)
with open("file.txt", 'r', encoding='utf-8') as f:
for line in f:
a = list(find_all(line,"==")
这很好用,它将找到“ ==”,但是我实际上需要它来查找在使用时以某种方式省略的空格:
a = list(find_all(line," "))
我需要做些什么改变才能找到空间?
答案 0 :(得分:0)
我不明白,这很完美:
list(find_all('This works perfectly doesn t it ?'," "))
[4, 10, 20, 26, 28, 31]
您能提供样品数据吗?也许您的空格是特殊字符?
我想你也看到了,但是以防万一:Find all occurrences of a substring in Python
答案 1 :(得分:0)
如上面的@Hoog所述,您在代码末尾缺少括号。
def find_all(a_str, sub):
start = 0
while True:
start = a_str.find(sub, start)
if start == -1: return
yield start
start += len(sub)
with open("file.txt", 'r', encoding='utf-8') as f:
for line in f:
a = list(find_all(line,"==")) # << Right here