0

Python has filter method which filters the desired output on some criteria as like in the following example.

>>> s = "some\x00string. with\x15 funny characters"
>>> import string
>>> printable = set(string.printable)
>>> filter(lambda x: x in printable, s)
'somestring. with funny characters'

The example is taken from link. Now, when I am trying to do similar thing in Python IDE it does return the result 'somestring. with funny characters' infact it return this <filter object at 0x0000020E1792EC50>. In IDE I cannot use just simple Enter so I am running this whole code with a print when filtering. Where I am doing it wrong? Thanks.

0

2 Answers 2

2

In python3 filter returns a generator (see docs)

You therefore normally want to convert this into a list to view its contents, or in your case, a string:

>>> s = "some\x00string. with\x15 funny characters"
>>> import string
>>> printable = set(string.printable)
>>> f = filter(lambda x: x in printable, s)
>>> ''.join(f)
'somestring. with funny characters'

The benefit of filter being an iterator, is that it uses much less memory. It can also easily be looped over, just like a list.

Sign up to request clarification or add additional context in comments.

Comments

2

In python 2.x filter returns a new list but on python 3.x it returns a filter object (generator), if you would like to see the results just call list(yourobject) for transform it into a list.

You must know that the python 3 version (as a generator) works lazily, alternatively you can use the itertools module for keep the behaviour on python 2 similar to python 3.

>>> list(itertools.ifilter(lambda x: x > 5, xrange(20)))
[6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

3 Comments

Actually in python2 filter special cases strings! Otherwise the result of filter(lambda x: True, "abc") would be ['a', 'b', 'c'] but actually is abc.
To be correct, filter in Python 2 returns can return either a list, a tuple or a string.
@BurhanKhalid That's not true. It special cases tuple and str. but for example filter(lambda x: True, {1,2,3}) == [1,2,3] so sets are converted to lists. Also if you have a namedtuple it will be converted to a plain tuple etc.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.