DEV Community

Harizio2
Harizio2

Posted on

Python: weird iterator behaviour after filtering out empty strings

I was fiddling around with Python trying to learn some basics and while making a string replacer script I ran across a weird problem.
The following script was supposed to replace all instances of "Input" by each element in subs and print out all the replaced strings.

text = """
MyInput = GetSubsystem<Input>();
extern Input* MyInput;
Input* MyInput = 0;
"""
texts = text.split("\n");
texts = filter(None,texts)#commenting this out fixes the iteration??
original = "Input";
subs = ["Time","WorkQueue","FileSystem","Log"]
sortbysubs = 1
separate = 0
print("number of subs:{} \n".format(len(subs)))
if (sortbysubs):
    for s in subs:
        for t in texts:
            print(t.replace(original,s))
        if separate:print("")
else:
    for t in texts:
        for s in subs:
            print(t.replace(original,s))
        if separate:print("")
Enter fullscreen mode Exit fullscreen mode

When sortbysubs = 0, it seems to work correctly: printing each line of text with each element in subs, and filtering out the empties beforehand.

When sortbysubs = 1, it only prints each text for the first element of subs.

Somehow there is a difference betweem printing "for s for t" rather than "for t for s".

Further more, this behaviour only emerges when filtering the texts for empties.
Commenting out the line "texts = filter(None,texts)" results in the problem disappearing.

Can anyone shed light on what exactly is happening here and how to fix it?

Top comments (1)

Collapse
 
harizio2 profile image
Harizio2

That makes sense!
Thanks for the help <3