Search code examples
pythonstrip

Python: cannot remove \n


I want to remove \n from the beginning lines like this \n id int(10) NOT NULL. I tried strip(), rstrip(), lstrip() replace('\n', ''). I don't get it. What am I doing wrong?

print(column)
print(column.__class__)
x = column.rstrip('\n')
print(x)
x = column.lstrip('\n')
print(x)            
x = column.strip('\n')          
print(x)
print(repr(column))

gives

\n  id int(10) NOT NULL
<type 'str'>
\n  id int(10) NOT NULL
\n  id int(10) NOT NULL
\n  id int(10) NOT NULL
\n  id int(10) NOT NULL
'\\n  `id` int(10) NOT NULL'

Solution

  • Are you sure that \n is a newline instead of a literal \ followed by a literal n? In that case, you'd want:

    s = r'\nthis is a string'
    s = s.strip()
    print s
    s = s.strip(r'\n')
    print s
    

    Probably a better way is to check if it starts with \n before stripping, and then use slicing:

    if s.startswith(r'\n'): s = s[2:]
    

    or even more robustly, re.sub:

    re.sub(r'^(?:\\n)+','',r'\n\nfoobar')
    

    Based on the symptoms you describe above, I'm almost positive this is the case.