write csv in python based on sub-string condition
<p>I have the following <code>result</code> variable in a data frame (<code>df</code>) and I am trying to output a csv file for those that starts with "test"</p>

<pre><code>abandoned
static
test_a_1
test_b_2
abandoned
test_b_3
</code></pre>

<p>The following code is not working. Thanks in advance for your insights</p>

<pre><code>substr="test"
if substr in df['result']:
    df.to_csv("C:/Projects/result.csv",sep=',',index=False)
</code></pre>

<p>Just because "test_a_1" is in the list does not mean that "test" is, 
in Python logic.</p>

<p>Example of how Python evaluates "if [string] in [list]" statements:</p>

<pre><code>&gt;&gt;&gt; test = 'test1'
&gt;&gt;&gt; testlist = ['test1', 'test2']
&gt;&gt;&gt; if 'test' in test:
...     print('hi')
... 
hi
&gt;&gt;&gt; if 'test' in testlist:
...     print('hi')
... 
&gt;&gt;&gt;
</code></pre>

<p>This would work:</p>

<pre><code>substr="test"
for val in df['result']:
    if substr in val:
        # Do stuff
        # And optionally (if you only need one CSV per dataframe rather than one CSV per result):
        break
</code></pre>

python string csv substring