How to prevent a particular string from being printed in find_all()?
<p>How to exclude a substring from being printed in object <code>obj</code></p>

<pre><code>obj = soup.find_all('tag')
if "string" not in obj.text:
    print obj.text
</code></pre>

<p>But due to the use of find_all() method for object obj nothing is being printed.
What should be done so that we print only the wanted string in obj.</p>

<p>You need to loop through the list returned by <code>find_all()</code>:</p>

<pre><code>for i in soup.find_all('tag'):
    txt = i.text
    if 'string' not in txt:
        print txt
</code></pre>

<p>Alternatively, you could create another list where the unwanted tags are filtered out:</p>

<pre><code>filtered_lst = [i for i in soup.find_all('tag') if 'string' not in i.text]
</code></pre>

<p>This will give you a list of <code>Tag</code> objects similar to that returned by <code>find_all()</code>, but with only the tags that do not include <code>'string'</code> in their <code>.text</code>. After that you can do what you want it it:</p>

<pre><code>for tag in filtered_lst:
    print tag.text
</code></pre>

<h1>Update:</h1>

<p>On the other hand, if your goal is to simply filter <code>'string'</code> from the text of the tag, you can use the <code>replace()</code> method of strings:</p>

<pre><code>for tag in soup.find_all('tag'):
    print tag.text.replace('string', '')
</code></pre>

<p>However, keep in mind that this will remove <code>'string'</code> wherever it is in the text, and may leave unwanted whitespace to be removed later. For example:</p>

<pre><code>&gt;&gt;&gt; 'hellostring string'.replace('string', '')
'hello '
</code></pre>

python web-scraping