st4rgut st4rgut - 1 month ago 6
Python Question

cannot remove newline from a string

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:

substring not found
. However, when i printed the value of cut it returned
kdfjsalsdjf
, showing the newlines code had been removed

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 "<pyshell#5>", line 3, in <module>
cut=x.index(i)
ValueError: substring not found

Answer

Why don't you use "replace" command?

x.replace("\n","")