DEV Community

Harizio2
Harizio2

Posted on

3 1

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?

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (1)

Collapse
 
harizio2 profile image
Harizio2

That makes sense!
Thanks for the help <3

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay