How can I replicate similar behaviour in python 3 as seen in python 2
<p>I have this operation done in <code>python 2</code>:</p>

<p>python 2:</p>

<pre><code>garbled = "IXXX aXXmX aXXXnXoXXXXXtXhXeXXXXrX sXXXXeXcXXXrXeXt mXXeXsXXXsXaXXXXXXgXeX!XX"

message = filter(lambda x: x != 'X', garbled)

print message
</code></pre>

<p>result:</p>

<pre><code>'I am another secret message!'
</code></pre>

<p>But in <code>python 3</code>:</p>

<pre><code>garbled = "IXXX aXXmX aXXXnXoXXXXXtXhXeXXXXrX sXXXXeXcXXXrXeXt mXXeXsXXXsXaXXXXXXgXeX!XX"

message = list(filter(lambda x: x != 'X', garbled))

print(message)
</code></pre>

<p>Result for `python 3:</p>

<pre><code>['I', ' ', 'a', 'm', ' ', 'a', 'n', 'o', 't', 'h', 'e', 'r', ' ', 's', 'e', 'c', 'r', 'e', 't', ' ', 'm', 'e', 's', 's', 'a', 'g', 'e', '!']
</code></pre>

<p>I want to know if its possible to get the same result in <code>python 3</code> as gotten in <code>python 2</code> from the <code>message</code> variable <code>without adding</code> a new line to the code in <code>python 3</code>. I already know the <code>join function</code>, I would like to make it as straight forward as seen in <code>the python 2 code</code>.</p>

<p>In python 3.X <code>filter()</code> returns an iterator and when you convert it to list you'll get a list of your characters. Thus, instead you can pass the iterator to <code>str.join()</code> method in order to join the filtered result together:</p>

<pre><code>In [1]: garbled = "IXXX aXXmX aXXXnXoXXXXXtXhXeXXXXrX sXXXXeXcXXXrXeXt mXXeXsXXXsXaXXXXXXgXeX!XX"

In [2]: message = ''.join(filter(lambda x: x != 'X', garbled))

In [3]: message
Out[3]: 'I am another secret message!'
</code></pre>

<p>But Note that using filter is not a proper way for removing a character, instead you can simply use <code>str.replace()</code>:</p>

<pre><code>In [4]: garbled.replace('X', '')
Out[4]: 'I am another secret message!'
</code></pre>

<p>Here is why <code>str.replace</code> is more pythonic:</p>

<pre><code>In [5]: %timeit''.join(filter(lambda x: x != 'X', garbled))
100000 loops, best of 3: 8.08 Âµs per loop

In [6]: %timeit garbled.replace('X', '')
1000000 loops, best of 3: 1.04 Âµs per loop
</code></pre>

python python-2.7 python-3.x