python-3.xstringfilter

Why does the str() not work on filter objects?


besthand = "AAAAJ"
besthand = str(filter("J".__ne__, besthand))

why is the type of besthand still a filter object? I've seen that you can use

besthand = "".join(besthand)

but I don't understand fully why str() doesn't work. Is it because filter objects are iterable?

P.S. I know it's close to being a duplicate, but I couldn't find a specific answer to this question


Solution

  • The "type of" besthand is no longer a filter, it's a string - because you used str() on it. But the default action of str() on many types in Python is the same as repr(), which is simply a description of the object but not its contents.

    In this case it couldn't show the contents even if it wanted to, because it hasn't processed the input yet. That only comes when you run the filter and do something with its output. That's exactly what you do with join().