0

I am reading a file line by line. I use a function to find specified characters in a line.

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,"==")

This works fine, it will find "==" but I actually need this to find spaces which are somehow omitted when I use:

a = list(find_all(line," "))

What change do I need to make to find spaces?

Seb_
  • 35
  • 7

2 Answers2

0

I don't understand, this works perfectly :

list(find_all('This works perfectly doesn t it ?'," "))
[4, 10, 20, 26, 28, 31]

Could you provide your sample data ? Maybe your spaces are special characters ?

Also, I suppose you saw this, but just in case : Find all occurrences of a substring in Python

Born Tbe Wasted
  • 610
  • 3
  • 13
  • Yes this actually works, not sure why it's not working in my other code. And yes, the link you provided is where I borrowed it from. – Seb_ Mar 26 '19 at 17:24
0

As @Hoog stated above, you are missing a parentheses at the end of your code.

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
David Culbreth
  • 2,610
  • 16
  • 26