cannot remove newline from a string
<p>Can you help me with this line of python code? I am trying to add strings to an array, and exclude the newlines. While the code appears to work the first time it splits the string, it seems to think there's another newline in there since it returns an error message: <code>substring not found</code>. However, when i printed the value of cut it returned <code>kdfjsalsdjf</code>, showing the newlines code had been removed</p>

<pre><code>x='lksjdfalkjdsflkajsdfkl\n\nkdfjsalsdjf'

for i in x:
    if i=='\n':
        cut=x.index(i)
        x=x[cut+2:]


Traceback (most recent call last):
  File "&lt;pyshell#5&gt;", line 3, in &lt;module&gt;
    cut=x.index(i)
ValueError: substring not found
</code></pre>

<p>Your problem stems from the fact that the <code>x</code> you iterate over does not see the changes you make.</p>

<p>It's somewhat like this:</p>

<pre><code>x = 'lksjdfalkjdsflkajsdfkl\n\nkdfjsalsdjf'
y = x
for i in x:
    if i=='\n':
        cut = y.index(i)
        y = y[cut+2:]
</code></pre>

<p>This is because of how <code>str.__iter__</code> works, and that therefore, changes you make to <code>x</code> within the for-loop are not reflected in future iterations of the for-loop.</p>

<p>You can fix this with a while-loop instead:</p>

<pre><code>i = 0
while &lt; len(x):
    if x[i] == '\n':
        x = x[i+2 :]
        i = -1
    i += 1
</code></pre>

<p>This is a bit convoluted, as it seems that you want to find the last occurrence of <code>'\n'</code>, and take whatever's 2 characters after it. So you could do this:</p>

<pre><code>x = 'lksjdfalkjdsflkajsdfkl\n\nkdfjsalsdjf'
inds = []
for i,char in enumerate(x):
    if char=='\n':
        inds.append(i)
if not inds:  # '\n' was nowhere in the string
    x = x  # we don't have to make any changes
else:
    max_ind = max(inds)
    x = x[max_ind+2 :]
</code></pre>

<p>Now, let's shorten this:</p>

<pre><code>x = 'lksjdfalkjdsflkajsdfkl\n\nkdfjsalsdjf'
inds = [i for i,char in enumerate(x) if char=='\n']
max_ind = max(inds)+2 if inds else -2
x = x[max_ind :]
</code></pre>

<p>Or:</p>

<pre><code>x = 'lksjdfalkjdsflkajsdfkl\n\nkdfjsalsdjf'
try:
    max_ind = x.rindex('\n')
    x = x[max_ind+2 :]
except ValueError:
    pass
</code></pre>

python