Python:无法删除\n

Ora*_*Tux 0 python strip

我想\n从头开始删除这样的行\n id int(10) NOT NULL.我试过strip(),rstrip(),lstrip() replace('\n', '').我不明白.我究竟做错了什么?

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))
Run Code Online (Sandbox Code Playgroud)

\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'
Run Code Online (Sandbox Code Playgroud)

mgi*_*son 8

你确定这\n是一个换行符而不是文字\后跟文字n吗?在这种情况下,你想要:

s = r'\nthis is a string'
s = s.strip()
print s
s = s.strip(r'\n')
print s
Run Code Online (Sandbox Code Playgroud)

可能更好的方法是检查它是否\n在剥离之前开始,然后使用切片:

if s.startswith(r'\n'): s = s[2:]
Run Code Online (Sandbox Code Playgroud)

甚至更强大,re.sub:

re.sub(r'^(?:\\n)+','',r'\n\nfoobar')
Run Code Online (Sandbox Code Playgroud)

根据你上面描述的症状,我几乎是肯定的.